工具类
package com.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
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.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MIME;
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.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
private static final int TIMEOUT_IN_MILLIONS = 10000;
/**
* Get请求,获得返回数据
*
*/
public static String doGet(String url, Map<String, Object> params) {
String result = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
if (MapUtils.isNotEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue()
.toString());
}
}
uriBuilder.setCharset(StandardCharsets.UTF_8);
HttpGet httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(setRequestConfig());
response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpclient);
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*响应结果
* @throws Exception
*/
public static String doPost(String url, String params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(setRequestConfig());
// List<NameValuePair> pairList = new ArrayList<NameValuePair>();
// if (MapUtils.isNotEmpty(params)) {
// for (Map.Entry<String, Object> entry : params.entrySet()) {
// NameValuePair pair = new BasicNameValuePair(entry.getKey(),
// entry.getValue().toString());
// pairList.add(pair);
// }
// }
HttpEntity entity = EntityBuilder
.create()
.setText(params)
// .setParameters(pairList)
.setContentType(ContentType.APPLICATION_JSON).build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
httpStr = EntityUtils.toString(response.getEntity(),
StandardCharsets.UTF_8);
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* post请求json数据
* @param url
* @param json
* @return
*/
public static JSONObject doPostJson(String url, JSONObject json){
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(response);
return response;
}
/**
* ssl的post同步請求
* @param url
* @param params
* @return
*/
public static String doPostSSL(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(createSSLConnectionManager())
.setDefaultRequestConfig(setRequestConfig()).build();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if (MapUtils.isNotEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),
entry.getValue().toString());
pairList.add(pair);
}
}
httpPost.setEntity(EntityBuilder
.create()
.setParameters(pairList)
.setContentType(
ContentType.create(URLEncodedUtils.CONTENT_TYPE,
MIME.UTF8_CHARSET)).build());
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consumeQuietly(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 发送 SSL GET 请求(HTTPS),K-V形式
*
* @param url
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doGetSSL(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(createSSLConnectionManager())
.setDefaultRequestConfig(setRequestConfig()).build();
HttpGet httpget = new HttpGet();
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpget.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if (MapUtils.isNotEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),
entry.getValue().toString());
pairList.add(pair);
}
}
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setParameters(pairList);
uriBuilder.setCharset(StandardCharsets.UTF_8);
httpget.setURI(uriBuilder.build());
response = httpClient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static PoolingHttpClientConnectionManager createSSLConnectionManager() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new HostnameVerifier() {
@Override
public boolean verify(String paramString,
SSLSession paramSSLSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http",
PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf).build();
// 设置连接池
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// Increase max total connection to 200
connMgr.setMaxTotal(100);
// Increase default max connection per route to 20
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
connMgr.setValidateAfterInactivity(TIMEOUT_IN_MILLIONS);
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(TIMEOUT_IN_MILLIONS).build();
connMgr.setDefaultSocketConfig(socketConfig);
return connMgr;
}
/**
* httpclient全局设置
*
* @return
*/
public static RequestConfig setRequestConfig() {
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(TIMEOUT_IN_MILLIONS);
// 设置读取超时
configBuilder.setSocketTimeout(TIMEOUT_IN_MILLIONS);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(TIMEOUT_IN_MILLIONS);
// 首先设置全局的标准cookie策略
configBuilder.setCookieSpec(CookieSpecs.STANDARD_STRICT);
return configBuilder.build();
}
}
maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.10</version>
</dependency>