SpringBoot 的 httpclient
转载 : http://lxgandlz.cn/400.html
配置类
/**
* Copyright (C), 深圳恩次方网络科技有限公司
* Author: zhouyang
* Date: 2018/5/14 0014 下午 5:40
* Description:
*/
package com.fishonline.easyreport.common;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyHttpClient {
@Value("${http.maxTotal}")
private Integer maxTotal;
@Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute;
@Value("${http.connectTimeout}")
private Integer connectTimeout;
@Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout;
@Value("${http.socketTimeout}")
private Integer socketTimeout;
@Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnabled;
/**
* 首先实例化一个连接池管理器,设置最大连接数、并发连接数
* @return
*/
@Bean(name = "httpClientConnectionManager")
public PoolingHttpClientConnectionManager getHttpClientConnectionManager(){
PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
//最大连接数
httpClientConnectionManager.setMaxTotal(maxTotal);
//并发数
httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return httpClientConnectionManager;
}
/**
* 实例化连接池,设置连接池管理器。
* 这里需要以参数形式注入上面实例化的连接池管理器
* @param httpClientConnectionManager
* @return
*/
@Bean(name = "httpClientBuilder")
public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")PoolingHttpClientConnectionManager httpClientConnectionManager){
//HttpClientBuilder中的构造方法被protected修饰,所以这里不能直接使用new来实例化一个HttpClientBuilder,可以使用HttpClientBuilder提供的静态方法create()来获取HttpClientBuilder对象
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(httpClientConnectionManager);
return httpClientBuilder;
}
/**
* 注入连接池,用于获取httpClient
* @param httpClientBuilder
* @return
*/
@Bean
public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder){
CloseableHttpClient httpClient = httpClientBuilder.build();
return httpClient;
}
/**
* Builder是RequestConfig的一个内部类
* 通过RequestConfig的custom方法来获取到一个Builder对象
* 设置builder的连接信息
* 这里还可以设置proxy,cookieSpec等属性。有需要的话可以在此设置
* @return
*/
@Bean(name = "builder")
public RequestConfig.Builder getBuilder(){
RequestConfig.Builder builder = RequestConfig.custom(); return builder.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout)
.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
}
/**
* 使用builder构建一个RequestConfig对象
* @param builder
* @return
*/
@Bean
public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
RequestConfig config = builder.build();
return config;
}
}
封装的功能类
/**
* Copyright (C), 深圳恩次方网络科技有限公司
* Author: zhouyang
* Date: 2018/5/14 0014 下午 5:46
* Description:
*/
package com.fishonline.easyreport.utils.Http;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class HttpAPIService {
//@Autowired
private CloseableHttpClient httpClient;
//@Autowired
private RequestConfig config;
public HttpAPIService(CloseableHttpClient httpClient,RequestConfig config){
this.httpClient = httpClient;
this.config = config;
}
/**
* 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url) throws Exception {
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(config);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}
/**
* 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍历map,拼接请求参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 调用不带参数的get请求
return this.doGet(uriBuilder.build().toString());
}
/**
* 带参数(表单)的post请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
// 判断map是否为空,不为空则进行遍历,封装from表单对象
if (map != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 构造from表单对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 把表单放到post里
httpPost.setEntity(urlEncodedFormEntity);
}
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
response.getEntity(), "UTF-8"));
}
/**
* 不带参数post请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
return this.doPost(url, null);
}
/**
* 带参数(json)的post请求
*
* @param url
* @param json
* @return
* @throws Exception
*/
public HttpResult doPostWithJSON(String url, JSONObject json,Map<String,String> headers) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
//设置 header
Header headerss[] = buildHeader(headers);
if(headerss != null && headerss.length > 0){
httpPost.setHeaders(headerss);
}
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
httpPost.setEntity(s);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
response.getEntity(), "UTF-8"));
}
/**
* 组装请求头
* @param params
* @return
*/
public static Header[] buildHeader(Map<String,String> params){
Header[] headers = null;
if(params != null && params.size() > 0){
headers = new BasicHeader[params.size()];
int i = 0;
for (Map.Entry<String, String> entry:params.entrySet()) {
headers[i] = new BasicHeader(entry.getKey(),entry.getValue());
i++;
}
}
return headers;
}
}
封装的结果类
/**
* Copyright (C), 深圳恩次方网络科技有限公司
* Author: zhouyang
* Date: 2018/5/14 0014 下午 5:45
* Description:
*/
package com.fishonline.easyreport.utils.Http;
public class HttpResult {
// 响应码
private Integer code;
// 响应体
private String body;
public HttpResult() {
super();
}
public HttpResult(Integer code, String body) {
super();
this.code = code;
this.body = body;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "HttpResult{" +
"code=" + code +
", body='" + body + '\'' +
'}';
}
}
使用代码
//封装json参数
HashMap map = new HashMap<String,String>();
map.put("account",company.getAdminPhone());
map.put("name",company.getAdminName());
map.put("userType",1);
map.put("company",companyId);
map.put("state",1);
JSONObject jsonObject = new JSONObject(map);
//发送添加user的请求
HttpAPIService httpAPIService = new HttpAPIService(httpClient,config);
//HttpAPIService httpAPIService = new HttpAPIService();
try {
Map<String,String> headers = new HashMap<String,String>();
//headers.put("Cookie", RequestContext.getHttpSession().getId());
HttpResult httpResult = httpAPIService.doPostWithJSON(url, jsonObject,headers);
System.out.println(httpResult);
} catch (Exception e) {
e.printStackTrace();
}*/
差不多 可能还有小问题..不要直接使用,提供参考
看到另一种发送请求的方法
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param paramMap 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, ?> paramMap) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
String param = "";
Iterator<String> it = paramMap.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
param += key + "=" + paramMap.get(key) + "&";
}
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw new ApplicationException();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}