├── README.md
├── src
└── main
│ ├── resources
│ └── application.properties
│ └── java
│ └── com
│ └── lxg
│ └── springboot
│ ├── SpringbootApplication.java
│ ├── controller
│ └── HttpClientController.java
│ ├── http
│ ├── HttpResult.java
│ ├── IdleConnectionEvictor.java
│ └── HttpAPIService.java
│ └── HttpClient.java
└── pom.xml
/README.md:
--------------------------------------------------------------------------------
1 | # springboot-httpclient
2 | ##SpringBoot整合HttpClient服务。
3 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li5454yong/springboot-httpclient/HEAD/src/main/resources/application.properties
--------------------------------------------------------------------------------
/src/main/java/com/lxg/springboot/SpringbootApplication.java:
--------------------------------------------------------------------------------
1 | package com.lxg.springboot;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringbootApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringbootApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/lxg/springboot/controller/HttpClientController.java:
--------------------------------------------------------------------------------
1 | package com.lxg.springboot.controller;
2 |
3 | import com.lxg.springboot.http.HttpAPIService;
4 | import org.springframework.web.bind.annotation.RequestMapping;
5 | import org.springframework.web.bind.annotation.RestController;
6 |
7 | import javax.annotation.Resource;
8 |
9 | /**
10 | * Created by lxg
11 | * on 2017/2/6.
12 | */
13 | @RestController
14 | public class HttpClientController {
15 |
16 | @Resource
17 | private HttpAPIService httpAPIService;
18 |
19 | @RequestMapping("httpclient")
20 | public String test() throws Exception {
21 | String str = httpAPIService.doGet("http://www.baidu.com");
22 | System.out.println(str);
23 | return "hello";
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/lxg/springboot/http/HttpResult.java:
--------------------------------------------------------------------------------
1 | package com.lxg.springboot.http;
2 |
3 | public class HttpResult {
4 |
5 | // 响应码
6 | private Integer code;
7 |
8 | // 响应体
9 | private String body;
10 |
11 | public HttpResult() {
12 | super();
13 | }
14 |
15 | public HttpResult(Integer code, String body) {
16 | super();
17 | this.code = code;
18 | this.body = body;
19 | }
20 |
21 | public Integer getCode() {
22 | return code;
23 | }
24 |
25 | public void setCode(Integer code) {
26 | this.code = code;
27 | }
28 |
29 | public String getBody() {
30 | return body;
31 | }
32 |
33 | public void setBody(String body) {
34 | this.body = body;
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/src/main/java/com/lxg/springboot/http/IdleConnectionEvictor.java:
--------------------------------------------------------------------------------
1 | package com.lxg.springboot.http;
2 |
3 | import org.apache.http.conn.HttpClientConnectionManager;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.stereotype.Component;
6 |
7 | @Component
8 | public class IdleConnectionEvictor extends Thread {
9 |
10 | @Autowired
11 | private HttpClientConnectionManager connMgr;
12 |
13 | private volatile boolean shutdown;
14 |
15 | public IdleConnectionEvictor() {
16 | super();
17 | super.start();
18 | }
19 |
20 | @Override
21 | public void run() {
22 | try {
23 | while (!shutdown) {
24 | synchronized (this) {
25 | wait(5000);
26 | // 关闭失效的连接
27 | connMgr.closeExpiredConnections();
28 | }
29 | }
30 | } catch (InterruptedException ex) {
31 | // 结束
32 | }
33 | }
34 |
35 | //关闭清理无效连接的线程
36 | public void shutdown() {
37 | shutdown = true;
38 | synchronized (this) {
39 | notifyAll();
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.lxg
8 | springboot-httpclient
9 | 1.0-SNAPSHOT
10 |
11 |
12 |
13 | aliyunRepository
14 | myRepository
15 | http://maven.aliyun.com/nexus/content/groups/public/
16 |
17 | false
18 |
19 |
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-parent
25 | 1.4.4.RELEASE
26 |
27 |
28 |
29 |
30 | UTF-8
31 | UTF-8
32 | 1.7
33 |
34 |
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-starter
39 |
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-test
44 | test
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-starter-web
50 |
51 |
52 |
53 | org.apache.httpcomponents
54 | httpclient
55 | 4.3.1
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 | org.springframework.boot
64 | spring-boot-maven-plugin
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/src/main/java/com/lxg/springboot/HttpClient.java:
--------------------------------------------------------------------------------
1 | package com.lxg.springboot;
2 |
3 | import org.apache.http.client.config.RequestConfig;
4 | import org.apache.http.impl.client.CloseableHttpClient;
5 | import org.apache.http.impl.client.HttpClientBuilder;
6 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
7 | import org.springframework.beans.factory.annotation.Qualifier;
8 | import org.springframework.beans.factory.annotation.Value;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.Configuration;
11 |
12 | /**
13 | * Created by admin on 2017/2/6.
14 | */
15 | @Configuration
16 | public class HttpClient {
17 |
18 | @Value("${http.maxTotal}")
19 | private Integer maxTotal;
20 |
21 | @Value("${http.defaultMaxPerRoute}")
22 | private Integer defaultMaxPerRoute;
23 |
24 | @Value("${http.connectTimeout}")
25 | private Integer connectTimeout;
26 |
27 | @Value("${http.connectionRequestTimeout}")
28 | private Integer connectionRequestTimeout;
29 |
30 | @Value("${http.socketTimeout}")
31 | private Integer socketTimeout;
32 |
33 | @Value("${http.staleConnectionCheckEnabled}")
34 | private boolean staleConnectionCheckEnabled;
35 |
36 | /**
37 | * 首先实例化一个连接池管理器,设置最大连接数、并发连接数
38 | * @return
39 | */
40 | @Bean(name = "httpClientConnectionManager")
41 | public PoolingHttpClientConnectionManager getHttpClientConnectionManager(){
42 | PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
43 | //最大连接数
44 | httpClientConnectionManager.setMaxTotal(maxTotal);
45 | //并发数
46 | httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
47 | return httpClientConnectionManager;
48 | }
49 |
50 | /**
51 | * 实例化连接池,设置连接池管理器。
52 | * 这里需要以参数形式注入上面实例化的连接池管理器
53 | * @param httpClientConnectionManager
54 | * @return
55 | */
56 | @Bean(name = "httpClientBuilder")
57 | public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")PoolingHttpClientConnectionManager httpClientConnectionManager){
58 |
59 | //HttpClientBuilder中的构造方法被protected修饰,所以这里不能直接使用new来实例化一个HttpClientBuilder,可以使用HttpClientBuilder提供的静态方法create()来获取HttpClientBuilder对象
60 | HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
61 |
62 | httpClientBuilder.setConnectionManager(httpClientConnectionManager);
63 |
64 | return httpClientBuilder;
65 | }
66 |
67 | /**
68 | * 注入连接池,用于获取httpClient
69 | * @param httpClientBuilder
70 | * @return
71 | */
72 | @Bean
73 | public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder){
74 | return httpClientBuilder.build();
75 | }
76 |
77 | /**
78 | * Builder是RequestConfig的一个内部类
79 | * 通过RequestConfig的custom方法来获取到一个Builder对象
80 | * 设置builder的连接信息
81 | * 这里还可以设置proxy,cookieSpec等属性。有需要的话可以在此设置
82 | * @return
83 | */
84 | @Bean(name = "builder")
85 | public RequestConfig.Builder getBuilder(){
86 | RequestConfig.Builder builder = RequestConfig.custom();
87 | return builder.setConnectTimeout(connectTimeout)
88 | .setConnectionRequestTimeout(connectionRequestTimeout)
89 | .setSocketTimeout(socketTimeout)
90 | .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
91 | }
92 |
93 | /**
94 | * 使用builder构建一个RequestConfig对象
95 | * @param builder
96 | * @return
97 | */
98 | @Bean
99 | public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
100 | return builder.build();
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/com/lxg/springboot/http/HttpAPIService.java:
--------------------------------------------------------------------------------
1 | package com.lxg.springboot.http;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | import org.apache.http.NameValuePair;
8 | import org.apache.http.client.config.RequestConfig;
9 | import org.apache.http.client.entity.UrlEncodedFormEntity;
10 | import org.apache.http.client.methods.CloseableHttpResponse;
11 | import org.apache.http.client.methods.HttpGet;
12 | import org.apache.http.client.methods.HttpPost;
13 | import org.apache.http.client.utils.URIBuilder;
14 | import org.apache.http.impl.client.CloseableHttpClient;
15 | import org.apache.http.message.BasicNameValuePair;
16 | import org.apache.http.util.EntityUtils;
17 | import org.springframework.beans.factory.annotation.Autowired;
18 | import org.springframework.stereotype.Component;
19 | import org.springframework.stereotype.Service;
20 |
21 |
22 | @Component
23 | public class HttpAPIService {
24 |
25 | @Autowired
26 | private CloseableHttpClient httpClient;
27 |
28 | @Autowired
29 | private RequestConfig config;
30 |
31 |
32 | /**
33 | * 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
34 | *
35 | * @param url
36 | * @return
37 | * @throws Exception
38 | */
39 | public String doGet(String url) throws Exception {
40 | // 声明 http get 请求
41 | HttpGet httpGet = new HttpGet(url);
42 |
43 | // 装载配置信息
44 | httpGet.setConfig(config);
45 |
46 | // 发起请求
47 | CloseableHttpResponse response = this.httpClient.execute(httpGet);
48 |
49 | // 判断状态码是否为200
50 | if (response.getStatusLine().getStatusCode() == 200) {
51 | // 返回响应体的内容
52 | return EntityUtils.toString(response.getEntity(), "UTF-8");
53 | }
54 | return null;
55 | }
56 |
57 | /**
58 | * 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
59 | *
60 | * @param url
61 | * @return
62 | * @throws Exception
63 | */
64 | public String doGet(String url, Map map) throws Exception {
65 | URIBuilder uriBuilder = new URIBuilder(url);
66 |
67 | if (map != null) {
68 | // 遍历map,拼接请求参数
69 | for (Map.Entry entry : map.entrySet()) {
70 | uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
71 | }
72 | }
73 |
74 | // 调用不带参数的get请求
75 | return this.doGet(uriBuilder.build().toString());
76 |
77 | }
78 |
79 | /**
80 | * 带参数的post请求
81 | *
82 | * @param url
83 | * @param map
84 | * @return
85 | * @throws Exception
86 | */
87 | public HttpResult doPost(String url, Map map) throws Exception {
88 | // 声明httpPost请求
89 | HttpPost httpPost = new HttpPost(url);
90 | // 加入配置信息
91 | httpPost.setConfig(config);
92 |
93 | // 判断map是否为空,不为空则进行遍历,封装from表单对象
94 | if (map != null) {
95 | List list = new ArrayList();
96 | for (Map.Entry entry : map.entrySet()) {
97 | list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
98 | }
99 | // 构造from表单对象
100 | UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
101 |
102 | // 把表单放到post里
103 | httpPost.setEntity(urlEncodedFormEntity);
104 | }
105 |
106 | // 发起请求
107 | CloseableHttpResponse response = this.httpClient.execute(httpPost);
108 | return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
109 | response.getEntity(), "UTF-8"));
110 | }
111 |
112 | /**
113 | * 不带参数post请求
114 | *
115 | * @param url
116 | * @return
117 | * @throws Exception
118 | */
119 | public HttpResult doPost(String url) throws Exception {
120 | return this.doPost(url, null);
121 | }
122 | }
--------------------------------------------------------------------------------