Java发起HTTP请求:使用Apache的HttpClient
许多小伙伴都喜欢用apache的HttpComponts里的HttpClient来向远程发起HTTP请求
从HttpComponents官网的features说明来看,当前版本(HttpClient4.5)仅支持到HTTP/1.1。 但是HttpCore.5.1BETA将支持HTTP/2,可惜还在BETA阶段。
使用方式:
项目中引入对应的maven依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
参考了别人的代码,简单使用:
/**
* 使用apache的HttpClient发起HTTP以及HTTPS请求
* 注意:当前的apache的HttpClient4.5只支持到HTTP/1.1
* 参考:https://zhuanlan.zhihu.com/p/69285935
* 参考:https://blog.csdn.net/happylee6688/article/details/47148227
*/
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;
static {
// 设置连接池
new PoolingHttpClientConnectionManager();
connMgr = // 设置连接池大小
setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
connMgr.
Builder configBuilder = RequestConfig.custom();
RequestConfig.// 设置连接超时
setConnectTimeout(MAX_TIMEOUT);
configBuilder.// 设置读取超时
setSocketTimeout(MAX_TIMEOUT);
configBuilder.// 设置从连接池获取连接实例的超时
setConnectionRequestTimeout(MAX_TIMEOUT);
configBuilder.// 在提交请求之前 测试连接是否可用
setStaleConnectionCheckEnabled(true);
configBuilder.build();
requestConfig = configBuilder.
}
/**
* 发送 GET 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
String result = null;
try {
//url上拼接参数
if (params != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
append(i == 0 ? "?" : "&");
param.append(key).append("=").append(params.get(key));
param.
i++;
}
url += param;
}// 通过址默认配置创建一个httpClient实例
@Cleanup CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
new HttpGet(url);
HttpGet httpGet = // 设置请求头信息示例(不需要可注释掉):鉴权
setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
httpGet.// 设置配置请求参数
/*RequestConfig requestConfig = RequestConfig.custom()
// 连接主机服务超时时间
.setConnectTimeout(35000)
// 请求超时时间
.setConnectionRequestTimeout(35000)
// 数据读取超时时间
.setSocketTimeout(60000)
.build();*/
// 为httpGet实例设置配置
setConfig(requestConfig);
httpGet.// 执行get请求得到返回对象
execute(httpGet);
HttpResponse response = httpClient.
int statusCode = response.getStatusLine().getStatusCode();
//System.out.println("执行状态码 : " + statusCode);
// 通过返回对象获取返回数据
getEntity();
HttpEntity entity = response.// 通过EntityUtils中的toString方法将结果转换为字符串
toString(entity);
result = EntityUtils.if (response != null) {
consume(response.getEntity());
EntityUtils.
}catch (ClientProtocolException e) {
} printStackTrace();
e.catch (IOException e) {
} printStackTrace();
e.
}return result;
}
/**
* 发送 GET 请求(HTTP),不带输入数据
*
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, null);
}
/**
* 发送 POST 请求(HTTP),K-V形式
*
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPost(String url, Map<String, Object> params) {
String result = "";
try {
// 创建httpClient实例
@Cleanup CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpPost远程连接实例
new HttpPost(url);
HttpPost httpPost = // 配置请求参数实例
/*RequestConfig requestConfig = RequestConfig.custom()
// 设置连接主机服务超时时间
.setConnectTimeout(35000)
// 设置连接请求超时时间
.setConnectionRequestTimeout(35000)
// 设置读取数据连接超时时间
.setSocketTimeout(60000)
.build();*/
// 为httpPost实例设置配置
setConfig(requestConfig);
httpPost.// 设置请求头示例(不需要可注释掉)
setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("Cookie", "id=123;token=234");
httpPost.// 封装post请求参数
//将传入post参数,转换为HttpClient可以接受的形式
if (params != null && params.size() > 0) {
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
getValue().toString());
.add(pair);
pairList.
}// 为httpPost设置封装好的请求参数
setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));
httpPost.
}// httpClient对象执行post请求,并返回响应参数对象
execute(httpPost);
HttpResponse httpResponse = httpClient.// 从响应对象中获取响应内容
getEntity();
HttpEntity entity = httpResponse.if (entity != null) {
toString(entity);
result = EntityUtils.
}catch (ClientProtocolException e) {
} printStackTrace();
e.catch (IOException e) {
} printStackTrace();
e.
}return result;
}
/**
* 发送 POST 请求(HTTP),JSON形式
*
* @param apiUrl
* @param json json对象
* @return
*/
public static String doPost(String apiUrl, String jsonStr) {
createDefault();
CloseableHttpClient httpClient = HttpClients.String httpStr = null;
new HttpPost(apiUrl);
HttpPost httpPost = null;
CloseableHttpResponse response = try {
setConfig(requestConfig);
httpPost.//解决中文乱码问题
new StringEntity(jsonStr, StandardCharsets.UTF_8);
StringEntity stringEntity = setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
stringEntity.setEntity(stringEntity);
httpPost.execute(httpPost);
response = httpClient.getEntity();
HttpEntity entity = response.//System.out.println(response.getStatusLine().getStatusCode());
toString(entity);
httpStr = EntityUtils.if (response != null) {
consume(response.getEntity());
EntityUtils.
}catch (IOException e) {
} printStackTrace();
e.
}return httpStr;
}
/**
* 发送 POST 请求(HTTP),不带输入数据
*
* @param apiUrl
* @return
*/
public static String doPost(String apiUrl) {
return doPost(apiUrl, (Map<String, Object>) null);
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
*
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPostSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient =custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpClients.new HttpPost(apiUrl);
HttpPost httpPost = null;
CloseableHttpResponse response = String httpStr = null;
try {
setConfig(requestConfig);
httpPost.List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
getValue().toString());
.add(pair);
pairList.
}setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));
httpPost.execute(httpPost);
response = httpClient.int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}getEntity();
HttpEntity entity = response.if (entity == null) {
return null;
}toString(entity, "utf-8");
httpStr = EntityUtils.if (response != null) {
consume(response.getEntity());
EntityUtils.
}catch (Exception e) {
} printStackTrace();
e.
}return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),JSON形式
*
* @param apiUrl API接口URL
* @param json JSON对象
* @return
*/
public static String doPostSSL(String apiUrl, Object json) {
CloseableHttpClient httpClient =custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpClients.new HttpPost(apiUrl);
HttpPost httpPost = null;
CloseableHttpResponse response = String httpStr = null;
try {
setConfig(requestConfig);
httpPost.//解决中文乱码问题
new StringEntity(json.toString(), "UTF-8");
StringEntity stringEntity = setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
stringEntity.setEntity(stringEntity);
httpPost.execute(httpPost);
response = httpClient.int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}getEntity();
HttpEntity entity = response.if (entity == null) {
return null;
}toString(entity, "utf-8");
httpStr = EntityUtils.if (response != null) {
consume(response.getEntity());
EntityUtils.
}catch (Exception e) {
} printStackTrace();
e.
}return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
null;
SSLConnectionSocketFactory sslsf = try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}build();
}).new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
sslsf = @Override
public boolean verify(String host, SSLSession session) {
return true;
}
});catch (GeneralSecurityException e) {
} printStackTrace();
e.
}return sslsf;
} }
测试:
class HttpClientUtilTest {
@Test
void doGet() {
System.out.println("Test doGet(): ");
String url = "https://httpbin.org/anything";
String res = HttpClientUtil.doGet(url);
System.out.println(res);
doGet(url + "?key1=value1&key2=value2");
res = HttpClientUtil.System.out.println(res);
Map<String, Object> params = new HashMap<>(8);
put("key1", "value1");
params.put("key2", "value2");
params.doGet(url, params);
res = HttpClientUtil.System.out.println(res);
}
@Test
void doPost() {
System.out.println("Test doPost(): ");
String url = "https://httpbin.org/anything";
String res = HttpClientUtil.doPost(url);
System.out.println(res);
Map<String, Object> params = new HashMap<>(8);
put("key1", "value1");
params.put("key2", "value2");
params.doPost(url, params);
res = HttpClientUtil.System.out.println(res);
new JsonMapper();
JsonMapper mapper = createObjectNode();
ObjectNode node = mapper.put("key1", "value1");
node.put("key2", "value2");
node.String jsonStr = node.toString();
doPost(url, jsonStr);
res = HttpClientUtil.System.out.println(res);
}
@Test
void doPostSSL() {
System.out.println("Test doPostSSL(): ");
String url = "https://httpbin.org/anything";
Map<String, Object> params = new HashMap<>(8);
put("key1", "value1");
params.put("key2", "value2");
params.String res = HttpClientUtil.doPostSSL(url, params);
System.out.println(res);
new JsonMapper();
JsonMapper mapper = createObjectNode();
ObjectNode node = mapper.put("key1", "value1");
node.put("key2", "value2");
node.String jsonStr = node.toString();
doPostSSL(url, jsonStr);
res = HttpClientUtil.System.out.println(res);
} }
发表回复