HttpClientUtil工具类
- POM依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
- java代码
package cn.pconline.utils;
import cn.pconline.BusinessException;
import cn.pconline.exeception.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;
/**
* @Description httpclient工具类
* @Author jie.zhao
* @Date 2019/7/24 12:13
*/
@Slf4j
public class HttpClientUtil {
public static final String METHOD_NAME_GET = "GET";
public static final String METHOD_NAME_POST = "POST";
/**
* 设置请求参数
*
* @param
* @return
*/
public static List<NameValuePair> setHttpParams(Map<String, Object> paramMap) {
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
Set<Map.Entry<String, Object>> set = paramMap.entrySet();
for (Map.Entry<String, Object> entry : set) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
return formParams;
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws KeyStoreException
*/
public static SSLConnectionSocketFactory createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) {
return true;
}
}).build();
return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
}
/**
* 设置代理
*
* @param
* @return
*/
public static RequestConfig setProxy(String host, Integer port) {
RequestConfig config;
if (host != null && port != null) {
HttpHost httpHost = new HttpHost(host, port);
config = RequestConfig.custom().setProxy(httpHost).build();
} else {
config = RequestConfig.custom().build();
}
return config;
}
/**
* Http GET请求方法 不使用代理、无参数
*
* @param url
* @return
*/
public static String httpGet(String url) {
return httpGet(url, null, null, null);
}
/**
* Http GET请求方法 不使用代理
*
* @param url
* @param paramMap
* @return
*/
public static String httpGet(String url, Map<String, Object> paramMap) {
return httpGet(url, paramMap, null, null);
}
/**
* Http GET请求方法 使用代理 需要自己传入代理Ip地址和端口
*
* @param url
* @param paramMap
* @return
*/
public static String httpGet(String url, Map<String, Object> paramMap, String host, Integer port) {
return baseHttp(METHOD_NAME_GET, url, paramMap, host, port);
}
/**
* Http POST请求方法 不使用代理、无参数
*
* @param url
* @return
*/
public static String httpPost(String url) {
return httpPost(url, null, null, null);
}
/**
* Http POST请求方法 不使用代理
*
* @param url
* @param paramMap
* @return
*/
public static String httpPost(String url, Map<String, Object> paramMap) {
return httpPost(url, paramMap, null, null);
}
/**
* Http POST请求方法 使用代理 需要自己传入代理Ip地址和端口
*
* @param url
* @param paramMap
* @return
*/
public static String httpPost(String url, Map<String, Object> paramMap, String host, Integer port) {
return baseHttp(METHOD_NAME_POST, url, paramMap, host, port);
}
/**
* 基础Http请求
*
* @param type
* @param url
* @param paramMap
* @param host
* @return
*/
public static String baseHttp(String type, String url, Map<String, Object> paramMap, String host, Integer port) {
CloseableHttpClient httpClient = null;
try {
if (!METHOD_NAME_GET.equalsIgnoreCase(type) && !METHOD_NAME_POST.equalsIgnoreCase(type)) {
throw new BusinessException(CodeEnum.PARAMETER_INVALID_OR_MISSING);
}
String content = "";
httpClient = HttpClients.custom().setSSLSocketFactory(createIgnoreVerifySSL()).build();
HttpResponse httpResponse;
if (METHOD_NAME_GET.equalsIgnoreCase(type)) {
httpResponse = httpClient.execute(createHttpGet(url, paramMap, host, port));
} else {
httpResponse = httpClient.execute(createHttpPost(url, paramMap, host, port));
}
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
content = EntityUtils.toString(entity, "UTF-8");
}
return content;
} catch (Exception e) {
e.printStackTrace();
log.error("httpRequest请求方法发生异常,msg{}", e.getMessage());
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 创建HttpGet
*
* @param url
* @param paramMap
* @param host
* @param port
* @return
*/
private static HttpGet createHttpGet(String url, Map<String, Object> paramMap, String host, Integer port) {
HttpGet httpGet = new HttpGet();
if (paramMap != null) {
List<NameValuePair> formParams = setHttpParams(paramMap);
String param = URLEncodedUtils.format(formParams, "UTF-8");
httpGet.setURI(URI.create(url + "?" + param));
} else {
httpGet.setURI(URI.create(url));
}
httpGet.setConfig(setProxy(host, port));
// 设置User-Agent
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
return httpGet;
}
/**
* 创建HttpPost
*
* @param url
* @param paramMap
* @param host
* @param port
* @return
*/
private static HttpPost createHttpPost(String url, Map<String, Object> paramMap, String host, Integer port) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(setProxy(host, port));
if (paramMap != null) {
UrlEncodedFormEntity param = new UrlEncodedFormEntity(setHttpParams(paramMap), "UTF-8");
httpPost.setEntity(param);
}
// 设置User-Agent
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
return httpPost;
}
}