GVKun编程网logo

httpclient 工具类,post 请求发送 json 字符串参数,中文乱码处理(httpclient发送json数据)

9

如果您对httpclient工具类,post请求发送json字符串参数,中文乱码处理和httpclient发送json数据感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解httpclient工具

如果您对httpclient 工具类,post 请求发送 json 字符串参数,中文乱码处理httpclient发送json数据感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解httpclient 工具类,post 请求发送 json 字符串参数,中文乱码处理的各种细节,并对httpclient发送json数据进行深入的分析,此外还有关于Android HttpClient,DefaultHttpClient,HttpPost、Apache HTTPClient以JSON为参数进行HTTPS POST请求、commons httpclient-将查询字符串参数添加到GET / POST请求、c#httpclient PostAsJson发送GET请求而不是POST的实用技巧。

本文目录一览:

httpclient 工具类,post 请求发送 json 字符串参数,中文乱码处理(httpclient发送json数据)

httpclient 工具类,post 请求发送 json 字符串参数,中文乱码处理(httpclient发送json数据)

在使用 httpclient 发送 post 请求的时候,接收端中文乱码问题解决。

正文:

我们都知道,一般情况下使用 post 请求是不会出现中文乱码的。可是在使用 httpclient 发送 post 请求报文含中文的时候在发送端数据正常但是到了服务器端就中文乱码了。

解决办法:

发送端进行设置编码如下:

 工具类:

 1 package com.Util;
 2 
 3 import com.google.common.base.Charsets;
 4 import org.apache.http.HttpEntity;
 5 import org.apache.http.client.methods.CloseableHttpResponse;
 6 import org.apache.http.client.methods.HttpPost;
 7 import org.apache.http.entity.StringEntity;
 8 import org.apache.http.impl.client.CloseableHttpClient;
 9 import org.apache.http.impl.client.HttpClients;
10 import org.apache.http.util.EntityUtils;
11 
12 public class HttpUtil {
13     public static String sendHttpPost(String url, String body) throws Exception {
14         CloseableHttpClient httpClient = HttpClients.createDefault();
15         HttpPost httpPost = new HttpPost(url);
16         httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
17         httpPost.setHeader("Accept", "application/json");
18         httpPost.setEntity(new StringEntity(body, Charsets.UTF_8));
19         CloseableHttpResponse response = httpClient.execute(httpPost);
20         System.out.println(response.getStatusLine().getStatusCode() + "\n");
21         HttpEntity entity = response.getEntity();
22         String responseContent = EntityUtils.toString(entity, "UTF-8");
23         response.close();
24         httpClient.close();
25         return responseContent;
26     }
27 
28 }

 

Android HttpClient,DefaultHttpClient,HttpPost

Android HttpClient,DefaultHttpClient,HttpPost

我如何将字符串数据( JSONObject.toString())发送到URL.我想在util类中编写一个静态方法来执行此操作.我希望方法签名如下

public static String postData(String url,String postData)抛出SomeCustomException

字符串url的格式应该是什么

返回String是来自服务器的响应,作为json数据的字符串表示.

编辑

目前的连接工具

package my.package;
import my.package.exceptions.CustomException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;

import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;


 public class ConnectionUtil {

 public static String postData(String url,String postData)
        throws CustomException {

    // Create a new HttpClient and Post Header
    InputStream is = null;
    StringBuilder sb = null;
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost();
    httppost.setHeader("host",url);

    Log.v("ConnectionUtil","opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url));

    try {
        httppost.setEntity(new StringEntity(postData));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        httpentity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag","Error in http connection " + e.toString());
        e.printstacktrace();
        throw new CustomException("Could not establish network connection");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is,"utf-8"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag","Error converting result " + e.toString());
        throw new CustomException("Error parsing the response");
    }
    Log.v("ConnectionUtil","Sent: "+postData);
    Log.v("ConnectionUtil","Got result "+result);
    return result;

}

}

Logcat输出

10-16 11:27:27.287: E/log_tag(4935): Error in http connection java.lang.NullPointerException
10-16 11:27:27.287: W/System.err(4935): java.lang.NullPointerException
10-16 11:27:27.287: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496)
10-16 11:27:27.307: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-16 11:27:27.327: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1)
10-16 11:27:27.327: W/System.err(4935): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-16 11:27:27.327: W/System.err(4935): at java.lang.Thread.run(Thread.java:1019)
10-16 11:27:27.327: V/log_tag(4935): Could not establish network connection

解决方法

我认为在您的代码中,基本问题是由您使用StringEntity将参数POST到网址的方式引起的.检查以下代码是否有助于使用StringEntity将数据发布到服务器.
// Build the JSON object to pass parameters
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username",username);
    jsonObj.put("data",dataValue);

    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObj.toString(),HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);

希望这有助于解决您的问题.谢谢.

Apache HTTPClient以JSON为参数进行HTTPS POST请求

Apache HTTPClient以JSON为参数进行HTTPS POST请求

HttpClient的请求很普遍,但有时我们更多地倾向于基于SSL安全的HTTP请求——HTTPS。接口在交互过程中,由于最初采用的是基于Spring的HttpClient请求方式,所以需要修改替换为HTTPS的请求方式。 参考代码

添加maven依赖配置

  <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.2.3</version>
		</dependency>
<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>

Apache HTTPS整理代码

package com.wlyd.fmcgwms.util.api;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
import com.wlyd.fmcgwms.util.Log;
import com.wlyd.fmcgwms.util.SAASTokenManager;
import com.wlyd.fmcgwms.util.ehcache.EhcacheUtil;
/**
 * Apache HttpClient JSON参数请求方式
 * 
 * @package com.wlyd.fmcgwms.util.api.APIHttpClient
 * @date   2016年11月11日  下午5:46:01
 * @author pengjunlin
 * @comment   
 * @update
 */
public class APIHttpClient {

	// 接口地址
	private String apiURL = "";
	
	private Log logger = Log.getLogger(getClass());
	
	private HttpClient httpClient = null;
	
	private HttpPost method = null;
	
	private long startTime = 0L;
	
	private long endTime = 0L;
	
	private int status = 0;

	/**
	 * 接口地址
	 * 
	 * @param url
	 */
	public APIHttpClient(String url) {
			this.apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", UUID.randomUUID().toString());
			
			//========================设置忽略访问SSL===================
			// 创建TrustManager
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}
				
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}
				
				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[] {};
				}
			};
			
			SSLContext ctx=null;
			try {
				ctx = SSLContext.getInstance("SSL");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
			try {
				ctx.init(null, new TrustManager[] { xtm }, null);
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			SSLSocketFactory sf = new SSLSocketFactory(
					ctx,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme sch = new Scheme("https", 443, sf);
			httpClient.getConnectionManager().getSchemeRegistry().register(sch);
	}
	
	/**
	 * 接口地址
	 * 
	 * @param url
	 * @param uuid
	 */
	public APIHttpClient(String url,String uuid) {
			apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", uuid);
			
			//========================设置忽略访问SSL===================
			// 创建TrustManager
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}
				
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}
				
				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[] {};
				}
			};
			
			SSLContext ctx=null;
			try {
				ctx = SSLContext.getInstance("SSL");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
			try {
				ctx.init(null, new TrustManager[] { xtm }, null);
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			SSLSocketFactory sf = new SSLSocketFactory(
					ctx,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme sch = new Scheme("https", 443, sf);
			httpClient.getConnectionManager().getSchemeRegistry().register(sch);
	}

	/**
	 * 调用 API
	 * 
	 * @param parameters
	 * @return
	 */
	public String post(String parameters) {
		String body = null;
		logger.info("parameters:" + parameters);

		if (method != null & parameters != null
				&& !"".equals(parameters.trim())) {
			JSONObject jsonObject = JSONObject.parseObject(parameters);
			logger.info("json:" + jsonObject.toString());
			try {

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// 建立一个NameValuePair数组,用于存储欲传送的参数
				params.add(new BasicNameValuePair("data", parameters));
				
				StringEntity entity=new StringEntity(parameters, "UTF-8");
				// 添加参数
				method.setEntity(entity/*new UrlEncodedFormEntity(params, "UTF-8")*/);

				startTime = System.currentTimeMillis();

				// 设置编码
				HttpResponse response = httpClient.execute(method);
				endTime = System.currentTimeMillis();
				int statusCode = response.getStatusLine().getStatusCode();
				logger.info("statusCode:" + statusCode);
				logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
				if (statusCode != HttpStatus.SC_OK) {
					logger.error("Method failed:" + response.getStatusLine());
					status = 1;
				}

				// Read the response body
				body = EntityUtils.toString(response.getEntity());

			} catch (IOException e) {
				// 发生网络异常
				logger.error("exception occurred!\n"
						+ ExceptionUtils.getFullStackTrace(e));
				// 网络错误
				status = 3;
			} finally {
				logger.info("调用接口状态:" + status);
			}

		}
		return body;
	}

	/**
	 * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
	 * 
	 * @return the status
	 */
	public int getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(int status) {
		this.status = status;
	}

	/**
	 * @return the startTime
	 */
	public long getStartTime() {
		return startTime;
	}

	/**
	 * @return the endTime
	 */
	public long getEndTime() {
		return endTime;
	}

}

简单重构之后

package com.wlyd.fmcgwms.util.api;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
import com.wlyd.fmcgwms.util.Log;
import com.wlyd.fmcgwms.util.SAASTokenManager;
import com.wlyd.fmcgwms.util.ehcache.EhcacheUtil;
/**
 * Apache HttpClient JSON参数请求方式
 * 
 * @package com.wlyd.fmcgwms.util.api.APIHttpClient
 * @date   2016年11月11日  下午5:46:01
 * @author pengjunlin
 * @comment   
 * @update
 */
public class APIHttpClient {

	// 接口地址
	private String apiURL = "";
	
	private Log logger = Log.getLogger(getClass());
	
	private HttpClient httpClient = null;
	
	private HttpPost method = null;
	
	private long startTime = 0L;
	
	private long endTime = 0L;
	
	private int status = 0;
	
	/**
	 * 设置忽略安全验证
	 * 
	 * @MethodName: initHttps 
	 * @Description: 
	 * @throws
	 */
	private void initHttps(){
		//========================设置忽略访问SSL===================
		// 创建TrustManager
		X509TrustManager xtm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
			
			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
			
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[] {};
			}
		};
		
		SSLContext ctx=null;
		try {
			ctx = SSLContext.getInstance("SSL");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
		try {
			ctx.init(null, new TrustManager[] { xtm }, null);
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		SSLSocketFactory sf = new SSLSocketFactory(
				ctx,
				SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		Scheme sch = new Scheme("https", 443, sf);
		httpClient.getConnectionManager().getSchemeRegistry().register(sch);
	}

	/**
	 * 接口地址
	 * 
	 * @param url
	 */
	public APIHttpClient(String url) {
			this.apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", UUID.randomUUID().toString());
			// 设置忽略访问SSL
			initHttps();
	}
	
	/**
	 * 接口地址
	 * 
	 * @param url
	 * @param uuid
	 */
	public APIHttpClient(String url,String uuid) {
			apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", uuid);
			// 设置忽略访问SSL
			initHttps();
	}

	/**
	 * 调用 API
	 * 
	 * @param parameters
	 * @return
	 */
	public String post(String parameters) {
		String body = null;
		logger.info("parameters:" + parameters);

		if (method != null & parameters != null
				&& !"".equals(parameters.trim())) {
			JSONObject jsonObject = JSONObject.parseObject(parameters);
			logger.info("json:" + jsonObject.toString());
			try {

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// 建立一个NameValuePair数组,用于存储欲传送的参数
				params.add(new BasicNameValuePair("data", parameters));
				
				StringEntity entity=new StringEntity(parameters, "UTF-8");
				// 添加参数
				method.setEntity(entity/*new UrlEncodedFormEntity(params, "UTF-8")*/);

				startTime = System.currentTimeMillis();

				// 设置编码
				HttpResponse response = httpClient.execute(method);
				endTime = System.currentTimeMillis();
				int statusCode = response.getStatusLine().getStatusCode();
				logger.info("statusCode:" + statusCode);
				logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
				if (statusCode != HttpStatus.SC_OK) {
					logger.error("Method failed:" + response.getStatusLine());
					status = 1;
				}

				// Read the response body
				body = EntityUtils.toString(response.getEntity());

			} catch (IOException e) {
				// 发生网络异常
				logger.error("exception occurred!\n"
						+ ExceptionUtils.getFullStackTrace(e));
				// 网络错误
				status = 3;
			} finally {
				logger.info("调用接口状态:" + status);
			}

		}
		return body;
	}

	/**
	 * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
	 * 
	 * @return the status
	 */
	public int getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(int status) {
		this.status = status;
	}

	/**
	 * @return the startTime
	 */
	public long getStartTime() {
		return startTime;
	}

	/**
	 * @return the endTime
	 */
	public long getEndTime() {
		return endTime;
	}

}

利用IDE 查看Apache HttpClient API

输入图片说明

编程小技巧

Maven给了我们许多方便,可以找到对应class以查看其源码。在这里有一个值得查看源码的情形是:在不知道API是否支持你所需要的数据类型时,第一是查看API的官方文档及其源码,第二就是对其源码进行改造以适应当前所需。

资源下载

Github地址

commons httpclient-将查询字符串参数添加到GET / POST请求

commons httpclient-将查询字符串参数添加到GET / POST请求

我正在使用Commons HttpClient对Spring servlet进行http调用。我需要在查询字符串中添加一些参数。因此,我执行以下操作:

HttpRequestBase request = new HttpGet(url);HttpParams params = new BasicHttpParams();params.setParameter("key1", "value1");params.setParameter("key2", "value2");params.setParameter("key3", "value3");request.setParams(params);HttpClient httpClient = new DefaultHttpClient();httpClient.execute(request);

但是,当我尝试使用读取servlet中的参数时

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getParameter("key");

它返回null。实际上parameterMap是完全空的。当我在创建HttpGet请求之前将参数手动添加到url时,该参数在servlet中可用。当我使用附加了queryString的URL从浏览器中访问servlet时也是如此。

这是什么错误?在httpclient 3.x中,GetMethod具有setQueryString()方法来追加查询字符串。4.x中的等效项是什么?

答案1

小编典典

这是使用HttpClient 4.2及更高版本添加查询字符串参数的方法:

URIBuilder builder = new URIBuilder("http://example.com/");builder.setParameter("parts", "all").setParameter("action", "finish");HttpPost post = new HttpPost(builder.build());

结果URI看起来像:

http://example.com/?parts=all&action=finish

c#httpclient PostAsJson发送GET请求而不是POST

c#httpclient PostAsJson发送GET请求而不是POST

我正在使用HttpClient发出发布请求。我回到405方法不被允许。在提琴手中捕获轨迹时,它作为GET而不是POST发出!

using (var client = new HttpClient())            {                var url = AppSettingsUtil.GetString("url");                var response = client.PostAsJsonAsync(url, transaction).Result;            }

我知道异步/等待问题。这是显示问题的简化示例。

是否存在某种可能会影响此的web.config或machine.config设置?其他请求(通过RestSharp发送)正确发送了帖子

这是提琴手捕获的东西。在提琴手中运行跟踪也会返回405(如预期)。手动将其切换为POST并从fiddler运行作品。

另外,也许因为方法已切换为GET,所以提琴手中没有捕获任何主体,所以我不得不手动粘贴到JSON中

GET /*URL*/ HTTP/1.1Content-Type: application/json; charset=utf-8Host: /*host*/Connection: Keep-Alive

答案1

小编典典

问题似乎是有人在未告知我们的情况下更改了URL,因此他们将重定向设置到位。HttpClient正在响应重定向,但实际上最终将请求作为Get发送到最终目的地。

在我看来,这似乎是HttpClient中的错误,它应该将最终请求作为Post发送,或者抛出异常,说它无法执行我要求的操作。

关于httpclient 工具类,post 请求发送 json 字符串参数,中文乱码处理httpclient发送json数据的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Android HttpClient,DefaultHttpClient,HttpPost、Apache HTTPClient以JSON为参数进行HTTPS POST请求、commons httpclient-将查询字符串参数添加到GET / POST请求、c#httpclient PostAsJson发送GET请求而不是POST等相关内容,可以在本站寻找。

本文标签: