package com.chinacreator.util;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
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.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
private static HttpClientUtil instance = null;
private HttpClientUtil(){}
public static HttpClientUtil getInstance(){
if (instance == null) {
instance = new HttpClientUtil();
}
return instance;
}
/**
*
* @param httpUrl
*/
public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl);// 鍒涘缓httpPost
if(httpUrl.startsWith("https")){
return sendHttpsPost(httpPost);
}else{
return sendHttpPost(httpPost);
}
}
/**
*
* @param httpUrl
* @param params (:key1=value1&key2=value2)
*/
public String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl);// 鍒涘缓httpPost
try {
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
e.printStackTrace();
}
if(httpUrl.startsWith("https")){
return sendHttpsPost(httpPost);
}else{
return sendHttpPost(httpPost);
}
}
/**
*
* @param httpUrl
* @param params (:key1=value1&key2=value2)
*/
public String sendHttpPostjson(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl);// 鍒涘缓httpPost
try {
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
e.printStackTrace();
}
if(httpUrl.startsWith("https")){
return sendHttpsPost(httpPost);
}else{
return sendHttpPost(httpPost);
}
}
/**
*
* @param httpUrl
* @param maps
*/
public String sendHttpPost(String httpUrl, Map<String, String> maps) {
HttpPost httpPost = new HttpPost(httpUrl);// httpPost
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
if(httpUrl.startsWith("https")){
return sendHttpsPost(httpPost);
}else{
return sendHttpPost(httpPost);
}
}
/**
*
* @param httpUrl
* @param maps
*/
public String sendHttpPost(HttpPost httpPost, Map<String, String> maps) {
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
public String sendHttpsPost(HttpPost httpPost) {
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
CloseableHttpClient httpClient = null;
try {
SSLContext sslcontext = createIgnoreVerifySSL();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",
new SSLConnectionSocketFactory(sslcontext)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
// httpclient
httpClient = HttpClients.custom().setConnectionManager(connManager)
.build();
httpPost.setConfig(requestConfig);
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(entity!=null){
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* @param httpPost
* @return
*/
public String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(entity!=null){
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* @param httpUrl
*/
public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);
return sendHttpGet(httpGet);
}
/**
* @param httpUrl
*/
public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);
return sendHttpsGet(httpGet);
}
/**
* @param httpPost
* @return
*/
public String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
entity = response.getEntity();
if(entity!=null){
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* @param httpPost
* @return
*/
public String sendHttp(HttpRequestBase http) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
http.setConfig(requestConfig);
response = httpClient.execute(http);
entity = response.getEntity();
if(entity!=null){
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* @param httpPost
* @return
*/
public String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
entity = response.getEntity();
if(entity!=null){
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
/**
* httpPut
*/
public String sendHttpPut(HttpPut httpPut) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
httpPut.setConfig(requestConfig);
response = httpClient.execute(httpPut);
entity = response.getEntity();
if(entity!=null){
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
}
调用代码(post接口)
在postman中调用成功即可用此util调用
String result = HttpClientUtil.getInstance().sendHttpPost("http://www.baidu.com?sn=f1&ak=1ab85e43d0&page=1&rows=20");