码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-03-07 19:36:54      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:puts   odi   end   pcl   eth   乱码   head   双向   回流   

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");

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

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

标签:puts   odi   end   pcl   eth   乱码   head   双向   回流   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!