Apache httpclient 使用
依赖
版本 4.5.13
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- HTTPclient上传文件 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
代码
package com.conformity.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
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 com.alibaba.fastjson.JSONObject;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
/**
* @author Admin
*
*/
public class HttpClientUtils {
/** get请求 相当于postman get请求 通过params传递参数
* @param url
* @param param
* @return
*/
public static String getUrlWithParam(String url,Map<String, String> param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpGet get = null;
String result = "";
StringBuilder sb = new StringBuilder();
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000) //连接超时 单位毫秒
.setSocketTimeout(5000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
.build();
try {
if (param != null && param.size() > 0) {
Set<String> keySet = param.keySet();
for (String key : keySet) {
String p = URLEncoder.encode(param.get(key),StandardCharsets.UTF_8.name());
sb.append(key+"="+p);
sb.append("&");
}
sb.deleteCharAt(sb.lastIndexOf("&"));
get = new HttpGet(url+"?"+sb.toString());
System.out.println(url+"?"+sb.toString());
}else {
get = new HttpGet(url);
}
get.setConfig(config);
response = httpClient.execute(get);
//本次请求是否成功
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
System.out.println("请求成功");
//获取响应头
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头---"+header.getName()+":"+header.getValue());
}
}else {
System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
}
//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数 有很多的实现
HttpEntity entity = response.getEntity();
//获取响应类型
System.out.println("ContentType:"+entity.getContentType());
result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
//确认流被关闭
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/**post表单请求 相当于postman 的表单上传 body中的application/x-www-form-urlencoded
* @param url
* @param map
* @return
*/
public static String postForm (String url,Map<String,Object> map) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost httpPost = null;
String result = "";
RequestConfig config = RequestConfig.custom()
.setProxy(new HttpHost("代理地址", 80))
.setConnectTimeout(5000) //连接超时 单位毫秒
.setSocketTimeout(5000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
.build();
try {
httpPost = new HttpPost(url);
//不设置时post请求默认就是这个
httpPost.addHeader("ContentType", "application/x-www-form-urlencoded; charset=UTF-8");
//post设置参数
if (map != null && map.size() > 0) {
List< NameValuePair> list = new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
list.add(new BasicNameValuePair(key, map.get(key).toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(list,StandardCharsets.UTF_8));
}
httpPost.setConfig(config);
response = httpClient.execute(httpPost);
//本次请求是否成功
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
System.out.println("请求成功");
//获取响应头
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头---"+header.getName()+":"+header.getValue());
}
}else {
System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
}
//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数 有很多的实现
HttpEntity entity = response.getEntity();
//获取响应类型
System.out.println("ContentType:"+entity.getContentType());
result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
//确认流被关闭
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/** post请求 json数据 相当于postman body中的form-data
* @param url
* @param map
* @return
*/
public static String postMap(String url,Map<String, Object> map) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost httpPost = null;
String result = "";
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000) //连接超时 单位毫秒
.setSocketTimeout(5000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
.build();
try {
httpPost = new HttpPost(url);
httpPost.addHeader("ContentType", "application/json; charset=UTF-8");
if (map != null && map.size() > 0) {
List<BasicNameValuePair> list = new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
BasicNameValuePair base = new BasicNameValuePair(key, map.get(key).toString());
list.add(base);
}
httpPost.setEntity(new UrlEncodedFormEntity(list, StandardCharsets.UTF_8.name()));
}
httpPost.setConfig(config);
response = httpClient.execute(httpPost);
//本次请求是否成功
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
System.out.println("请求成功");
//获取响应头
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头---"+header.getName()+":"+header.getValue());
}
}else {
System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
}
//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数 有很多的实现
HttpEntity entity = response.getEntity();
//获取响应类型
System.out.println("ContentType:"+entity.getContentType());
result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
//确认流被关闭
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/**post请求 json数据 相当于postman body 中的raw json格式
* @param url
* @param params
* @return
*/
public static String postJson(String url, JSONObject params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost httpPost = null;
String result = "";
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000) //连接超时 单位毫秒
.setSocketTimeout(5000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
.build();
try {
httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
//设置请求类型为json
httpPost.addHeader("ContentType", "application/json; charset=UTF-8");
StringEntity jsonEntity = new StringEntity(params.toJSONString(), Consts.UTF_8);
//给参数实体设置内容类型
jsonEntity.setContentType("application/json; charset=UTF-8");
//设置编码类型 防止乱码
jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
}
httpPost.setConfig(config);
response = httpClient.execute(httpPost);
//本次请求是否成功
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
System.out.println("请求成功");
//获取响应头
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头---"+header.getName()+":"+header.getValue());
}
}else {
System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
}
//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数 有很多的实现
HttpEntity entity = response.getEntity();
//获取响应类型
System.out.println("ContentType:"+entity.getContentType());
result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
//确认流被关闭
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/**post请求 绕过https安全认证
* @param url
* @param params
* @return
*/
public static String postJsonSSL(String url, JSONObject params) {
Registry<ConnectionSocketFactory> registry = null;
try {
//获取注册中心 注册协议
registry = RegistryBuilder.<ConnectionSocketFactory>create().
register("http", PlainConnectionSocketFactory.INSTANCE).
register("https", TrustCertificate()).
build();
} catch (Exception e) {
e.printStackTrace();
return "";
}
//创建HTTPclient连接池
PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
//传入连接池 创建 HttpClientBuilder
HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pool);
//通过HttpClientBuilder创建CloseableHttpClient
CloseableHttpClient httpClient = builder.build();
CloseableHttpResponse response = null;
HttpPost httpPost = null;
String result = "";
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(40000) //连接超时 单位毫秒
.setSocketTimeout(40000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(40000) //从连接池获取connection的超时时间
.build();
try {
httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
//设置请求类型为json
httpPost.addHeader("ContentType", "application/json; charset=UTF-8");
StringEntity jsonEntity = new StringEntity(params.toJSONString(), Consts.UTF_8);
//给参数实体设置内容类型
jsonEntity.setContentType("application/json; charset=UTF-8");
//设置编码类型 防止乱码 这里不能设置 会报错
// jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
}
httpPost.setConfig(config);
response = httpClient.execute(httpPost);
//本次请求是否成功
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数 有很多的实现
HttpEntity entity = response.getEntity();
//获取响应类型
System.out.println("ContentType:"+entity.getContentType());
result = EntityUtils.toString(entity,StandardCharsets.UTF_8);
//确认流被关闭
EntityUtils.consume(entity);
return result;
}else {
result = "";
return result;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
@SuppressWarnings("deprecation")
private static ConnectionSocketFactory TrustCertificate() throws Exception{
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[] {"SSLv2Hello","SSLv3","TLSv1","TLSv1.1","TLSv1.2"},
null,NoopHostnameVerifier.INSTANCE);
return sslConnectionSocketFactory;
}
/** 下载图片
* @param url 图片路径
* @param path 存储路径
* @return
*/
public static boolean getFile(String url,String path) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
OutputStream os = null;
HttpGet get = null;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000) //连接超时 单位毫秒
.setSocketTimeout(5000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
.build();
try {
get = new HttpGet(url);
response = httpClient.execute(get);
//本次请求是否成功
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
System.out.println("请求成功");
}else {
System.out.println("请求失败:"+response.getStatusLine().getStatusCode());
return false;
}
get.setConfig(config);
//HttpEntity 不仅可以作为请求的结果 ,也可以作为请求参数 有很多的实现
HttpEntity entity = response.getEntity();
//获取响应类型
// image/jpg image/jpeg image/png image/图片的后缀
String contentType = entity.getContentType().getValue();
String suffix = ".jpg";
if (contentType.contains("jpg") || contentType.contains("jpeg")) {
suffix = ".jpg";
}else if(contentType.contains("png")) {
suffix = ".png";
}else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
suffix = ".bmp";
}else if (contentType.contains("gif")) {
suffix = ".gif";
}
//获取文件字节流
String uuid = IdUtil.simpleUUID();
byte[] byteArray = EntityUtils.toByteArray(entity);
os = new FileOutputStream(new File(path+File.separator+uuid+suffix));
os.write(byteArray);
os.flush();
//确认流被关闭
EntityUtils.consume(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/** 上传图片 相当于postman的表单提交数据
* @param url
* @param inputStream
* @param params
* @return
*/
public static String postFile(String url,File[] files,Map<String, String> params) {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost httpPost = null;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000) //连接超时 单位毫秒
.setSocketTimeout(5000) //读取数据超时 单位毫秒
.setConnectionRequestTimeout(5000) //从连接池获取connection的超时时间
.build();
try {
httpPost = new HttpPost(url);
httpPost.setConfig(config);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//设置内容格式
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
//设置字符集编码
builder.setCharset(StandardCharsets.UTF_8);
//设置浏览器模式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//通过流获取文件
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
builder.addBinaryBody("files", files[i]);
}
}
//设置普通文本参数 含有中文时不推荐使用 可能会乱码
// builder.addTextBody("phone", "111111111", ContentType.TEXT_PLAIN);
if (MapUtil.isNotEmpty(params)) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
//设置中文参数时 使用这个
builder.addPart(key, new StringBody(params.get(key),ContentType.create("text/plain", StandardCharsets.UTF_8)));
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("接口成功发送");
}else {
return "接口发送失败";
}
result = EntityUtils.toString(response.getEntity());
return result;
} catch (Exception e) {
e.printStackTrace();
result = "系统异常";
return result;
}finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}