HttpClient

https://www.ibm.com/developerworks/cn/opensource/os-httpclient/

IBM这篇讲解的比较规范、清晰。

http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html

http://blog.csdn.net/wangpeng047/article/details/19624529

这两篇给出了HttpClient的各种应用。

 

HttpClient 4.3的变化较大,譬如getMethod/postMethod用HttpGet/HttpPost取代。

PostMethod和HttpPost的区别

 

旧版

 1 public class HttpTests {  
 2     /** 
 3      * @param args 
 4      * @throws Exception 
 5      */  
 6     public static void main(String[] args) throws Exception {  
 7         HttpClient httpclient = new HttpClient();  
 8         PostMethod httpPost =new PostMethod("******/abc");  
 9         NameValuePair[] param = { new NameValuePair("username", "vip")};  
10         httpPost.setRequestBody(param);   
11         httpclient.executeMethod(httpPost);  
12     }  
13 } 

 

新版 

 1 public static String getMes(String url, String params) {  
 2     CloseableHttpClient client = HttpClients.createDefault();  
 3     HttpPost htPost = new HttpPost(url);  
 4     String backMes = null;  
 5     try {  
 6         htPost.setHeader("content-type", "application/json");  
 7         StringEntity reqEntity = new StringEntity(params);  
 8         htPost.setEntity(reqEntity);  
 9         HttpResponse httpResponse = client.execute(htPost);  
10         HttpEntity entity = httpResponse.getEntity();  
11         backMes = EntityUtils.toString(entity, "UTF-8").toString();  
12     } catch (ClientProtocolException e) {  
13         // TODO Auto-generated catch block  
14         e.printStackTrace();  
15     } catch (IOException e) {  
16         // TODO Auto-generated catch block  
17         e.printStackTrace();  
18     } finally {  
19         try {  
20             client.close();  
21             client = null;  
22         } catch (IOException e) {  
23             // TODO Auto-generated catch block  
24             e.printStackTrace();  
25         }  
26     }  
27     return backMes;  
28 }

 

 

posted @ 2016-12-07 12:05  唐公子  阅读(251)  评论(0编辑  收藏  举报