httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求

1.httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求。

http 连接一次就有返回流。http是个双向的嘛。只有连接了,就会有输出返回流。

所以在执行http连接的时候,返回值都是http连接的返回流。

HttpResponse response = client.execute(httpPost);

2.http发送,body里是可以写入中文的。但要注意乱码问题:

  1. public static String getHttpRequestString(String url,String body) throws IOException {  
  2.         HttpClient client = new DefaultHttpClient();  
  3.         HttpPost httpPost = new HttpPost(url);  
  4.   
  5.         StringEntity stringEntity = new StringEntity(body);  
  6.         httpPost.setEntity(stringEntity);  
  7.         httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");  
  8.   
  9.         HttpResponse response = client.execute(httpPost);  
  10.         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
  11.         String line;  
  12.         StringBuffer jsonString = new StringBuffer();  
  13.         while((line = bufferedReader.readLine()) != null) {  
  14.             jsonString.append(line);  
  15.         }  
  16.         return jsonString.toString();  
  17.     }  

这是最初的代码,如果传输的body有中文汉字的话,如果对方设置的格式是UTF-8,那么他接收到的字符是乱码,

stringEntity.setContentEncoding("UTF-8");

加上这样一句代码,设置下格式就好了。

原文地址:https://www.cnblogs.com/panxuejun/p/6516193.html