HttpClient通信

1.背景

大多数系统功能和代码都是自己写的,自己用,但是在有些情况下,我们可以利用已经存在的系统,完成对自己实现相对很麻烦的功能,这些一般代价相对较大,自己不可能专门写一个系统或者太过很复杂的代码来完成不会经常用的功能。这时候就可以利用httpClient通信,在获得允许的情况下,安全的获取别的系统的服务。例如利用别的邮件系统发邮件,查询手机号码归属之类的功能。

2.之前有比较老版本的httpClient,现在旧的已经不提供更新了,apache 根据功能新分解出httpClient和httpCore,maven:

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
 </dependency>
  新版本的使用更复杂,但是却相对安全很多。

官网有新版的快速教程:http://hc.apache.org/httpcomponents-client-ga/

3.整个api很复杂,详细了解很需要耐心和时间,这里也不建议大家学的那么细,毕竟用的时候不会太多,也不会用的那么复杂,可以在需要的时候,不懂还可以查api和官网教程。

我也没有看的很深入,只是大致写了几个简单的demo,觉得深入学习很需要时间。这里是一个很基本的上手例子:

 1 package org.mj.commonsHttpClient;  
 2 
 3 import java.io.IOException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import org.apache.http.HttpEntity;
 8 import org.apache.http.NameValuePair;
 9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.entity.UrlEncodedFormEntity;
11 import org.apache.http.client.fluent.Form;
12 import org.apache.http.client.fluent.Request;
13 import org.apache.http.client.methods.CloseableHttpResponse;
14 import org.apache.http.client.methods.HttpGet;
15 import org.apache.http.client.methods.HttpPost;
16 import org.apache.http.impl.client.CloseableHttpClient;
17 import org.apache.http.impl.client.HttpClients;
18 import org.apache.http.message.BasicNameValuePair;
19 import org.apache.http.util.EntityUtils;
20 
21 /** 
22  * @author jing.ming
23  * @version 创建时间:2015年11月26日 上午9:03:06 
24  * 使用最新的httpClient4.5.x
25  */
26 public class HttpClientNewVersion {
27 
28     public static void getMethodTry() throws IOException {
29         CloseableHttpClient httpclient = HttpClients.createDefault();
30         HttpGet httpGet = new HttpGet("http://httpbin.org/get");
31         CloseableHttpResponse response1 = httpclient.execute(httpGet);
32         // The underlying HTTP connection is still held by the response object
33         // to allow the response content to be streamed directly from the
34         // network socket.
35         // In order to ensure correct deallocation of system resources
36         // the user MUST call CloseableHttpResponse#close() from a finally
37         // clause.
38         // Please note that if response content is not fully consumed the
39         // underlying
40         // connection cannot be safely re-used and will be shut down and
41         // discarded
42         // by the connection manager.
43         try {
44             System.out.println(response1.getStatusLine());
45             HttpEntity entity1 = response1.getEntity();
46             // do something useful with the response body
47             // and ensure it is fully consumed
48             EntityUtils.consume(entity1);
49         } finally {
50             response1.close();
51         }
52     }
53 
54     public static void postMethodTry() throws ClientProtocolException, IOException{
55         CloseableHttpClient httpclient = HttpClients.createDefault();
56         HttpPost httpPost = new HttpPost("http://httpbin.org/post");
57         List <NameValuePair> nvps = new ArrayList <NameValuePair>();
58         nvps.add(new BasicNameValuePair("username", "vip"));
59         nvps.add(new BasicNameValuePair("password", "secret"));
60         httpPost.setEntity(new UrlEncodedFormEntity(nvps));
61         CloseableHttpResponse response2 = httpclient.execute(httpPost);
62 
63         try {
64             System.out.println(response2.getStatusLine());
65             HttpEntity entity2 = response2.getEntity();
66             // do something useful with the response body
67             // and ensure it is fully consumed
68             EntityUtils.consume(entity2);
69         } finally {
70             response2.close();
71         }
72     }
73 
74     // fluent API ,更简单的处理方式
75     // The fluent API relieves the user from having to deal with manual
76     // deallocation of system
77     // resources at the cost of having to buffer response content in memory in
78     // some cases.
79     public static void fluentMode() throws ClientProtocolException, IOException {
80         Request.Get("http://targethost/homepage").execute().returnContent();
81         Request.Post("http://targethost/login")
82                 .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
83                 .execute().returnContent();
84     }
85     
86     public static void main(String[] args) {
87         try {
88             getMethodTry();
89         } catch (ClientProtocolException e) {
90             e.printStackTrace();
91         } catch (IOException e) {
92             e.printStackTrace();
93         }
94     }
95 
96 }
97  

 

posted on 2015-11-26 19:15  明静  阅读(813)  评论(0编辑  收藏  举报

导航