``
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.*;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
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.HttpDelete;
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.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
public class HttpUtil {
private static final int MAX_TOTAL = 50;
private static final int MAX_PERROUTE = 20;
private static final int EXECUTION_COUNT = 3;
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
public static String get(String url, Map<String, String> headers, Integer connectTime, Integer socketTimeout,
Boolean isRetry, Integer retryCount) throws IOException, org.apache.http.conn.HttpHostConnectException,
ParseException {
int cTimeout = 5000;
int sTimeout = 5000;
if (connectTime != null) {
cTimeout = connectTime.intValue();
}
if (socketTimeout != null) {
sTimeout = socketTimeout.intValue();
}
CloseableHttpClient httpClient = getCloseableHttpClient(isRetry, retryCount);
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(cTimeout).setSocketTimeout(sTimeout).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
if (null != headers) {
Set<Entry<String, String>> entrys = headers.entrySet();
for (Entry<String, String> each : entrys) {
httpGet.setHeader(each.getKey(), each.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
String strResult = EntityUtils.toString(entity);
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
return strResult;
}
public static CloseableHttpClient getCloseableHttpClient(final Boolean isRetry, final Integer retryCount) {
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
final int retryCount_ = (null == retryCount ? EXECUTION_COUNT : retryCount);
if (null != isRetry && isRetry == true) {
if (executionCount > retryCount_) {
return false;
}
}
if (exception instanceof SocketTimeoutException) {
System.out.println("Sockettimout retry>>>>>>>>");
return true;
}
if (exception instanceof org.apache.http.conn.ConnectTimeoutException) {
System.out.println("ConnectTimeoutException retry>>>>>>>>");
return true;
}
if (exception instanceof InterruptedIOException) {
return false;
}
if (exception instanceof UnknownHostException) {
return false;
}
if (exception instanceof ConnectTimeoutException) {
System.out.println(" org.apache.commons.httpclient.ConnectTimeoutException retry.....");
return true;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
return true;
}
return false;
}
};
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(MAX_TOTAL);
cm.setDefaultMaxPerRoute(MAX_PERROUTE);
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
.setSoTimeout(5000).setTcpNoDelay(true).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultSocketConfig(socketConfig)
.setRetryHandler(retryHandler).setConnectionManager(cm).build();
return httpClient;
}
public static String sendHttpDelete(String url) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig config = null;
try {
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1)
.setSoReuseAddress(true).setSoTimeout(5000).setTcpNoDelay(true).build();
httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
int connectTimeout = 5000;
int socketTimeout = 20000;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.build();
httpDelete.setConfig(config);
response = httpClient.execute(httpDelete);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} finally {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return responseContent;
}
public static String sendHttpPost(String httpUrl, Map<String, Object> params, Map<String, String> headers)
throws ClientProtocolException, IOException, ParseException {
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.setRedirectsEnabled(true).build();
HttpPost httpPost = new HttpPost(httpUrl);
httpPost.setConfig(config);
if (params != null) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? "" : entry.getValue().toString();
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
return sendHttpPost(httpPost);
}
private static String sendHttpPost(HttpPost httpPost) throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = createSSLClientDefault();
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} finally {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return responseContent;
}
public static Map<String, String> sendHttpPost(String httpUrl, Map<String, Object> params,
Map<String, String> headers, String headerName) throws ParseException, ClientProtocolException, IOException {
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
HttpPost httpPost = new HttpPost(httpUrl);
httpPost.setConfig(config);
if (params != null) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? "" : entry.getValue().toString();
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
return sendHttpPost(httpPost, headerName);
}
public static Map<String, String> sendHttpPostWithRedirect(String httpUrl, Map<String, Object> params,
Map<String, String> headers, String headerName) throws ParseException, ClientProtocolException, IOException {
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.setRedirectsEnabled(true).build();
HttpPost httpPost = new HttpPost(httpUrl);
httpPost.setConfig(config);
if (params != null) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? "" : entry.getValue().toString();
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
return sendHttpPost(httpPost, headerName);
}
public static CloseableHttpClient getHttpClient() {
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
.setSoTimeout(5000).setTcpNoDelay(true).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
return httpClient;
}
public static String get(String url, Map<String, String> params, Map<String, String> headers)
throws ParseException, ClientProtocolException, IOException {
CloseableHttpClient httpClient = createSSLClientDefault();
CloseableHttpResponse response = null;
InputStream inputStream = null;
try {
if (params != null) {
StringBuilder sb = new StringBuilder("?");
for (Entry<String, String> entry : params.entrySet()) {
String value = URLEncoder.encode(entry.getValue(), "UTF-8");
value = value.replaceAll("\\+", "%20");
sb.append(entry.getKey()).append("=").append(value).append("&");
}
sb.delete(sb.length() - 1, sb.length());
url += sb.toString();
}
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (entity.isStreaming()) {
inputStream = entity.getContent();
if (inputStream != null) {
return consumeInputStream(inputStream);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return null;
}
private static Map<String, String> sendHttpPost(HttpPost httpPost, String headerName)
throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
Map<String, String> map = new HashMap<String, String>();
try {
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1)
.setSoReuseAddress(true).setSoTimeout(5000).setTcpNoDelay(true).build();
httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
map.put("content", responseContent);
Header[] responseHeaders = response.getHeaders(headerName);
if (responseHeaders != null && responseHeaders.length > 0) {
String headerValue = responseHeaders[0].getValue();
map.put(headerName, headerValue);
}
} finally {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return map;
}
public static String putJson(String url, JSONObject jsonParam, Boolean isRetry, Integer retryCount)
throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
InputStream inputStream = null;
try {
httpClient = getCloseableHttpClient(isRetry, retryCount);
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.build();
HttpPut httpPut = new HttpPut(url);
httpPut.setConfig(config);
httpPut.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(jsonParam.toString(), "utf-8");
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpPut.setEntity(se);
response = httpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (entity.isStreaming()) {
inputStream = entity.getContent();
if (inputStream != null) {
return consumeInputStream(inputStream);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return null;
}
public static String postJson(String url, String requestBody,Map<String, String> headers) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = createSSLClientDefault();
CloseableHttpResponse response = null;
InputStream inputStream = null;
try {
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config = null;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
httpPost.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(requestBody, "utf-8");
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
if (!CollectionUtils.isEmpty(headers)) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (entity.isStreaming()) {
inputStream = entity.getContent();
if (inputStream != null) {
return consumeInputStream(inputStream);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return null;
}
public static String getJson(String url, Map<String, String> headers) throws ClientProtocolException, IOException, ParseException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
InputStream inputStream = null;
try {
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false).setSoLinger(1).setSoReuseAddress(true)
.setSoTimeout(5000).setTcpNoDelay(true).build();
httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).build();
int connectTimeout = 5000;
int socketTimeout = 20000;
RequestConfig config;
config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
httpGet.setHeader("Accept", "application/json");
if (!CollectionUtils.isEmpty(headers)) {
for (Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (entity.isStreaming()) {
inputStream = entity.getContent();
if (inputStream != null) {
return consumeInputStream(inputStream);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return null;
}
private static String consumeInputStream(InputStream in) throws IOException {
StringBuilder out = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1; ) {
out.append(new String(b, 0, n));
}
return out.toString();
}
@SuppressWarnings("rawtypes")
public static JSONObject doPost(String urlStr, Map<String, String> textMap, Map<String, MultipartFile> fileMap) {
JSONObject jsonObject = null;
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
MultipartFile inputValue = (MultipartFile) entry.getValue();
if (inputValue == null) {
continue;
}
String filename = inputValue.getOriginalFilename();
String contentType = inputValue.getContentType();
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\";filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
InputStream in = inputValue.getInputStream();
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
InputStream inputStream = null;
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK ) {
inputStream = conn.getErrorStream();
} else {
inputStream = conn.getInputStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
String result = new String(buffer);
jsonObject = JSONObject.parseObject(result);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return jsonObject;
}
}