maven地址:
<!--HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
配置HttpClientConfig :
@Configuration
public class HttpClientConfig {
private Integer maxTotal = 200;
private Integer defaultMaxPerRoute = 20;
private Integer connectTimeout = 20000;
private Integer connectionRequestTimeout = 20000;
private Integer socketTimeout = 20000;
@Bean(name = "httpClientConnectionManager")
public PoolingHttpClientConnectionManager getHttpClientConnectionManager(){
PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
httpClientConnectionManager.setMaxTotal(maxTotal);
httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return httpClientConnectionManager;
}
@Bean(name = "httpClientBuilder")
public HttpClientBuilder getHttpClientBuilder(
@Qualifier("httpClientConnectionManager") PoolingHttpClientConnectionManager httpClientConnectionManager){
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(httpClientConnectionManager);
return httpClientBuilder;
}
@Bean
public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder){
return httpClientBuilder.build();
}
@Bean(name = "builder")
public RequestConfig.Builder getBuilder(){
RequestConfig.Builder builder = RequestConfig.custom();
return builder.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout).setCookieSpec(CookieSpecs.STANDARD_STRICT);
}
@Bean
public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
return builder.build();
}
}
使用HttpClient:
@Component
public class HttpClientUtil {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig requestConfig;
//httpClientConnectionManager post 线程池请求 applicationo/json
public HttpClientVo doPost(String url, Map<String, String> headerMap,String cookie, String contentMap) {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
//添加请求头
Iterator<Map.Entry<String, String>> headIterator = headerMap.entrySet().iterator();
while (headIterator.hasNext()) {
Map.Entry<String, String> next = headIterator.next();
httpPost.addHeader(next.getKey(), next.getValue());
}
//加入cookie
if (StringUtils.isNotBlank(cookie)) {
httpPost.setHeader("Cookie", cookie);
}
try {
if (StringUtils.isNotBlank(contentMap)) {
StringEntity entity = new StringEntity(contentMap,"utf-8");
httpPost.setEntity(entity);
}
//执行返回结果
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
}
httpPost.abort();
} catch (Exception e) {
httpPost.abort();
return "fail";
}
}
//httpClientConnectionManager post 线程池请求 application/x-www-form-urlencoded
public HttpClientVo doPost(String url, Map<String, String> headerMap,String cookie, Map<String, String> contentMap) {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
//添加请求头
Iterator<Map.Entry<String, String>> headIterator = headerMap.entrySet().iterator();
while (headIterator.hasNext()) {
Map.Entry<String, String> next = headIterator.next();
httpPost.addHeader(next.getKey(), next.getValue());
}
//加入cookie
if (StringUtils.isNotBlank(cookie)) {
httpPost.setHeader("Cookie", cookie);
}
//设置body
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : contentMap.entrySet()){
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
//执行返回结果
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
}
httpPost.abort();
} catch (Exception e) {
httpPost.abort();
return "fail";
}
}
//文件上传请求
public HttpClientVo uploadFile(MultipartFile file, String url) {
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 创建待处理的文件
String fileName = file.getOriginalFilename();
ContentBody files = new ByteArrayBody(file.getBytes(), fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", files);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null && response.getStatusLine().getStatusCode() == 200) {
// 将响应内容转换为字符串
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF- 8"));
}
httpPost.abort();
} catch (Exception e) {
httpPost.abort();
logger.error("error");
}
}
}