项目中经常会用到模拟Http请求,而jdk 下的 rt.jar核心库中也有 java.net提供了这方面的功能,但是总体而言,功能还是缺少灵活性和全面性,HttpClient的出现就是弥补了其缺失的功能。HttpClient不是浏览器客户端,而是一个客户端和服务端实现通信的Http组件库。本篇文章主要讲解CloseableHttpClient 的使用。
1. 项目中添加依赖的jar包
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.5version>
<exclusions>
<exclusion>
<artifactId>commons-codecartifactId>
<groupId>commons-codecgroupId>
exclusion>
exclusions>
dependency>
2.1 模拟HttpGet请求
/**
* 模拟HttpGet 请求
* @param url
* @return
*/
public static String HttpGet(String url){
//单位毫秒
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000).setConnectTimeout(3000)
.setSocketTimeout(3000).build();//设置请求的状态参数
CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpGet);//返回请求执行结果
int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
if (statusCode != HttpStatus.SC_OK) {
return null;
} else {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
return result;
}
} catch (Exception e) {
logger.error("httpget Exception handle-- > " + e);
} finally {
if (response != null){
try {
response.close();//关闭response
} catch (IOException e) {
logger.error("httpget IOException handle-- > " + e);
}
}
if(httpclient != null){
try {
httpclient.close();//关闭httpclient
} catch (IOException e) {
logger.error("httpget IOException handle-- > " + e);
}
}
}
return null;
}
2.2 模拟HttpPost请求
/**
* 模拟HttpPost请求
* @param url
* @param jsonString
* @return
*/
public static String HttpPost(String url, String jsonString){
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();//创建CloseableHttpClient
HttpPost httpPost = new HttpPost(url);//实现HttpPost
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpPost.setConfig(requestConfig); //设置httpPost的状态参数
httpPost.addHeader("Content-Type", "application/json");//设置httpPost的请求头中的MIME类型为json
StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
httpPost.setEntity(requestEntity);//设置请求体
try {
response = httpClient.execute(httpPost, new BasicHttpContext());//执行请求返回结果
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
return resultStr;
} else {
return null;
}
} catch (Exception e) {
logger.error("httpPost method exception handle-- > " + e);
return null;
} finally {
if (response != null){
try {
response.close();//最后关闭response
} catch (IOException e) {
logger.error("httpPost method IOException handle -- > " + e);
}
}if(httpClient != null){try {httpClient.close();} catch (IOException e) {logger.error("httpPost method exception handle-- > " + e);}
}
}
}
不设置参数的简版写法:
public byte[] get(String url) {
CloseableHttpResponse response = null;
try {
HttpGet httpget = new HttpGet(url);
response = httpClient.execute(httpget);
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
return out.toByteArray();
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
} catch (IOException e) {
logger.error("httpClient --> simpleGet IO超时", e);
throw BusinessException.asBusinessException(BusinessErrorCode.HTTP_IO_EXCEPTION);
} catch (Exception e) {
logger.error("httpClient --> simpleGet 未知异常", e);
throw BusinessException.asBusinessException(BusinessErrorCode.HTTP_UNKNOWN_EXCEPTION);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException var3) {
logger.error("closeResponse execute error!!");
}
}
}
}
public String simplePost(String url, String stringEntity) {
logger.info("httpClient -> simplePost start, url={},stringEntity={}", url, stringEntity);
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
StringEntity paramEntity = new StringEntity(stringEntity);
paramEntity.setContentEncoding("UTF-8");
paramEntity.setContentType("application/json");
httpPost.setEntity(paramEntity);
response = httpClient.execute(httpPost);
logger.info("httpClient -> simplePost, response={},s={}", response.toString(), JsonUtil.toJSONString(response));
logger.info("");
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity httpEntity = response.getEntity();
return EntityUtils.toString(httpEntity, defaultCharset);//取出应答字符串
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
} catch (IOException e) {
logger.error("httpClient --> simplePost IO超时", e);
throw BusinessException.asBusinessException(BusinessErrorCode.HTTP_IO_EXCEPTION);
} catch (Exception e) {
logger.error("httpClient --> simplePost 未知异常", e);
throw BusinessException.asBusinessException(BusinessErrorCode.HTTP_UNKNOWN_EXCEPTION);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException var3) {
logger.error("closeResponse execute error!!");
}
}
}
}
需要注意的是:如果参数 stringEntity 想以对象的形式作为入参,要这样写,使用JSONObject创建对象:
List<String> testList = new ArrayList();
testList.add("testString123");
JSONObject jsonObject = new JSONObject();
jsonObject.put("testList",testList);
String stringEntity = jsonObject.toJSONString();
而不能这样写,这样写是一个字符串,不是对象:
String stringEntity = sonUtil.toJSONString(testList);