前言
在和其它一些联合编程的时候,我们经常需要调用第三方和其它一些系统的接口,那么httpClient的出现就很好的解决了这个问题,下面将对常用的httpClient请求进行演示。
一、引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
二、httpClient请求
1.GET请求
Get不携带数据请求代码(示例):
public static String httpToGet(String baseUrl) throws Exception {
//可关闭的httpClient客户端,相当于你打开的一个浏览器
CloseableHttpClient aDefault = HttpClients.createDefault();
//接受参数
String toStringResult = null;
//构造请求对象
HttpGet httpGet = new HttpGet(baseUrl);
//解决httpClient被认为不是真人行为
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36");
//构造响应对象
CloseableHttpResponse response = null;
try {
response = aDefault.execute(httpGet);
//代表本次请求的成功、失败的状态,响应码为200则表示成功。
StatusLine statusLine = response.getStatusLine();
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
//获取响应实体
HttpEntity entity = response.getEntity();
//对HttpEntity操作的工具类,获取返回的数据
toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
//确保流关闭
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (aDefault != null) {
try {
aDefault.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return toStringResult;
}
GET携带数据请求代码(示例):
public static String httpToGetParam(String baseUrl, HashMap<String,Object> paramMap){
//可关闭的httpClient客户端,相当于你打开的一个浏览器
CloseableHttpClient aDefault = HttpClients.createDefault();
//拼接请求参数
StringBuilder urlStr = new StringBuilder();
urlStr.append(baseUrl).append("?");
for (Map.Entry<String, Object> param : paramMap.entrySet()) {
urlStr.append(param.getKey()).append("=")
.append(param.getValue()).append("&");
}
//构造请求对象
HttpGet httpGet = new HttpGet(urlStr.toString());
//解决httpClient被认为不是真人行为
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36");
//构造响应对象
CloseableHttpResponse response = null;
//接受响应参数
String toStringResult=null;
try {
response = aDefault.execute(httpGet);
//代表本次请求的成功、失败的状态
StatusLine statusLine = response.getStatusLine();
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
//获取响应实体
HttpEntity entity = response.getEntity();
//对HttpEntity操作的工具类
toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
//确保流关闭
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (aDefault != null) {
try {
aDefault.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return toStringResult;
}
}
2.POST请求
POST携带数据请求代码(示例):
public static String postToParam(String url, JSONObject param) {
//可关闭的httpClient客户端,相当于你打开的一个浏览器
CloseableHttpClient aDefault = HttpClients.createDefault();
//构造请求对象
HttpPost httpPost = new HttpPost(url);
//设置请求体格式
StringEntity jsonEntity = new StringEntity(param.toString(), Consts.UTF_8);
//也需要给entity设置一下内容类型
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
//下方这种是默认的发送模式,但是平时我们的请求基本是上面这种请求模式
//jsonEntity.setContentType(new BasicHeader("Content-Type","application/x-www-from-urlencoded;charset=UTF-8"));
//如果想要使用请求头携带数据,那么可以直接设置
//httpPost.addHeader("填写携带的数据的名称","填写携带的数据的具体参数");
//设置entity的编码
jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
//构造响应对象
CloseableHttpResponse response = null;
//接受响应实体
String toStringResult = null;
try {
response = aDefault.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
//获取响应实体
HttpEntity entity = response.getEntity();
//对HttpEntity操作的工具类
toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringResult);
//确保流关闭
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (aDefault != null) {
try {
aDefault.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return toStringResult;
}
3.PUT请求
PUT携带数据请求代码(示例):
public static String putToParam(String url, JSONObject param) {
//可关闭的httpClient客户端,相当于你打开的一个浏览器
CloseableHttpClient aDefault = HttpClients.createDefault();
//构造请求对象
HttpPut httpPost = new HttpPut(url);
//设置请求体格式
StringEntity jsonEntity = new StringEntity(param.toString(), Consts.UTF_8);
//也需要给entity设置一下内容类型
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
//下方这种是默认的发送模式,但是平时我们的请求基本是上面这种请求模式
//jsonEntity.setContentType(new BasicHeader("Content-Type","application/x-www-from-urlencoded;charset=UTF-8"));
//如果想要使用请求头携带数据,那么可以直接设置
//httpPost.addHeader("填写携带的数据的名称","填写携带的数据的具体参数");
//设置entity的编码
jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
//构造响应对象
CloseableHttpResponse response = null;
//接受响应实体
String toStringResult = null;
try {
response = aDefault.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
//获取响应实体
HttpEntity entity = response.getEntity();
//对HttpEntity操作的工具类
toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringResult);
//确保流关闭
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (aDefault != null) {
try {
aDefault.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return toStringResult;
}
三、httpClient使用代理请求
/**
* 参数描述:
* @url 请求地址
* @param 发送的数据
* @proxyIp 代理主机ip
* @proxyPort 代理主机端口
*/
public static String postToParamByProxy(String url, JSONObject param,String proxyIp,String proxyPort) {
//可关闭的httpClient客户端,相当于你打开的一个浏览器
CloseableHttpClient aDefault = HttpClients.createDefault();
//构造请求对象
HttpPost httpPost = new HttpPost(url);
//不同形式的请求,设置代理的方式都一样(get,put,post),需要设置代理,只需要加上下面这段配置即可
//设置代理对象
HttpHost httpHost = new HttpHost(proxyIp,Integer.parseInt(proxyPort));
RequestConfig build = RequestConfig.custom()
.setProxy(httpHost)//设置代理对象
.setConnectTimeout(3000)//设置连接超时时间,单位:毫秒 可以自行根据需要设置,也可以不设置
.setConnectionRequestTimeout(3000)//设置链接请求超时时间,单位:毫秒
.build();
httpPost.setConfig(build);
//设置请求体格式
StringEntity jsonEntity = new StringEntity(param.toString(), Consts.UTF_8);
//也需要给entity设置一下内容类型
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
//下方这种是默认的发送模式,但是平时我们的请求基本是上面这种请求模式
//jsonEntity.setContentType(new BasicHeader("Content-Type","application/x-www-from-urlencoded;charset=UTF-8"));
//如果想要使用请求头携带数据,那么可以直接设置
//httpPost.addHeader("填写携带的数据的名称","填写携带的数据的具体参数");
//设置entity的编码
jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
//构造响应对象
CloseableHttpResponse response = null;
//接受响应实体
String toStringResult = null;
try {
response = aDefault.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
//获取响应实体
HttpEntity entity = response.getEntity();
//对HttpEntity操作的工具类
toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringResult);
//确保流关闭
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (aDefault != null) {
try {
aDefault.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return toStringResult;
}