该工具类可传输普通参数、文件等。
pom文件
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
工具类
HttpClientUtils
package com.infoPublish.service.http;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
/**
* httpClient工具类
*
* @author mzp
*
*/
public class HttpClientUtils {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 3000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 6000 * 10 * 15;
private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
private static final String CONTENT_TYPE = "application/json;charset=UTF-8";
private static Logger logger = LogManager.getLogger(HttpClientUtils.class);
/**
* 发送get请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
*/
public static HttpClientResult doGet(String url) {
return doGet(url, null, null);
}
/**
* 发送get请求;带请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @return
*/
public static HttpClientResult doGet(String url, Map<String, String> params) {
return doGet(url, null, params);
}
/**
* 发送get请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
*/
public static HttpClientResult doGet(String url,
Map<String, String> headers,
Map<String, String> params){
HttpClientResult httpClientResult = new HttpClientResult();
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问的地址
URIBuilder uriBuilder;
try {
uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。 setConnectionRequestTimeout:设置从connect
* Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
} catch (URISyntaxException e) {
//e.printStackTrace();
logger.error("发送get请求出错", e);
httpClientResult.setContent("发生URISyntaxException异常");
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
return httpClientResult;
}
/**
* 发送get请求;返回图片
* @param url
* @param filePath 图片路径
* @return true 成功 false 失败
*/
public static boolean doGet(String url, String filePath){
boolean result = false;
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问的地址
URIBuilder uriBuilder;
try {
uriBuilder = new URIBuilder(url);
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。 setConnectionRequestTimeout:设置从connect
* Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求
try {
httpResponse = httpClient.execute(httpGet);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
if (httpResponse.getEntity() != null) {
try {
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream inputStream = httpResponse.getEntity().getContent();
if(inputStream != null) {
FileOutputStream out = new FileOutputStream(filePath);
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while ((len = inputStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
out.write(buffer, 0, len);
}
if(out != null) {
out.close();
}
result = true;
}
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
// 释放资源
release(httpResponse, httpClient);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送post请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
*/
public static HttpClientResult doPost(String url) {
return doPostMethod(url, null, null);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @return
*/
public static HttpClientResult doPost(String url,
Map<String, String> params) {
return doPost(url, null, params);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
*/
public static HttpClientResult doPost(String url,
Map<String, String> headers,
Map<String, String> params) {
HttpEntity formEntity = null;
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
formEntity = new UrlEncodedFormEntity(nvps, Charset.forName(ENCODING));
}
return doPostMethod(url, headers, formEntity);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param paramJson json请求参数
* @return
*/
public static HttpClientResult doPost(String url,
JSONObject paramJson) {
return doPost(url, null, paramJson);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @return
*/
public static HttpClientResult doPost(String url,
Map<String, String> headers,
JSONObject paramJson) {
StringEntity se = null;
if(paramJson != null) {
if(headers == null) {
headers = new HashMap<>();
}
headers.put("Content-Type", CONTENT_TYPE);
se = new StringEntity(paramJson.toString(),
Charset.forName(ENCODING));
se.setContentType(CONTENT_TYPE_TEXT_JSON);
}
return doPostMethod(url, headers, se);
}
/**
* 发送post请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param formEntity 请求参数
* @return
*/
public static HttpClientResult doPostMethod(String url,
Map<String, String> headers,
HttpEntity formEntity) {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。 setConnectionRequestTimeout:设置从connect
* Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpPost);
// 设置到请求的http对象中
if(formEntity != null) {
httpPost.setEntity(formEntity);
}
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 上传多个文件
* @param url
* @param files
* @param mapParams
* @return
*/
public static HttpClientResult upload(String url,
Set<File> files,
Map<String, String> mapParams){
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。 setConnectionRequestTimeout:设置从connect
* Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
int count = 1;
for (File file:files) {
builder.addBinaryBody("f"+count, file);
count++;
}
if(mapParams != null) {
for (Entry<String, String> entry : mapParams.entrySet()) {
builder.addTextBody(entry.getKey(), entry.getValue());//设置请求参数
}
}
httpPost.setEntity(builder.build());
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @return
*/
public static HttpClientResult doPut(String url) {
return doPut(url, null);
}
/**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params json参数
* @return
*/
public static HttpClientResult doPut(String url, JSONObject params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
if(params != null) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", CONTENT_TYPE);
headers.put("DataEncoding", ENCODING);
packageHeader(headers, httpPut);
StringEntity se = new StringEntity(params.toString(),
Charset.forName(ENCODING));
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httpPut.setEntity(se);
}
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;不带请求参数
*
* @param url 请求地址
* @return
*/
public static HttpClientResult doDelete(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
/**
* 封装请求头
*
* @param params 参数
* @param httpMethod 请求方式
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) {
HttpClientResult httpClientResult = new HttpClientResult();
// 执行请求
try {
try {
httpResponse = httpClient.execute(httpMethod);
}catch(ConnectTimeoutException e) {
//e.printStackTrace();
logger.error("获得响应结果失败", e);
httpClientResult.setContent("连接超时");
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
try {
content = EntityUtils.toString(httpResponse.getEntity(),
Charset.forName(ENCODING));
httpClientResult.setCode(httpResponse.getStatusLine().getStatusCode());
httpClientResult.setContent(content);
} catch (ParseException e) {
//e.printStackTrace();
logger.error("获得响应结果失败", e);
httpClientResult.setContent("发生ParseException异常");
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} catch (IOException e) {
//e.printStackTrace();
logger.error("获得响应结果失败", e);
httpClientResult.setContent("发生IOException异常");
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
}
}
} catch (ClientProtocolException e) {
//e1.printStackTrace();
logger.error("获得响应结果失败", e);
httpClientResult.setContent("发生ClientProtocolException异常 " + e.getMessage());
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} catch (IOException e) {
//e1.printStackTrace();
logger.error("获得响应结果失败", e);
httpClientResult.setContent("发生IOException异常 " + e.getMessage());
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} catch (Exception e) {
//e1.printStackTrace();
logger.error("获得响应结果失败", e);
httpClientResult.setContent("发生IOException异常 " + e.getMessage());
httpClientResult.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
return httpClientResult;
}
/**
* 释放资源
*
* @param httpResponse
* @param httpClient
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient){
// 释放资源
try {
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
HttpClientResult
package com.infoPublish.service.http;
/**
* 封装httpClient响应结果
* @author mzp
*
*/
public class HttpClientResult {
//响应状态码
private int code;
//响应数据
private String content;
public HttpClientResult() {
}
public HttpClientResult(int code) {
this.code = code;
}
public HttpClientResult(int code, String content) {
this.code = code;
this.content = content;
}
@Override
public String toString() {
return "HttpClientResult [code=" + code + ", content=" + content + "]";
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}