HttpsUtil.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. package com.xzl.web.utils;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.config.RequestConfig;
  6. import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. import org.apache.http.client.methods.*;
  8. import org.apache.http.client.utils.URIBuilder;
  9. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  10. import org.apache.http.conn.ssl.SSLContextBuilder;
  11. import org.apache.http.conn.ssl.TrustStrategy;
  12. import org.apache.http.entity.ContentType;
  13. import org.apache.http.entity.StringEntity;
  14. import org.apache.http.entity.mime.MultipartEntityBuilder;
  15. import org.apache.http.entity.mime.content.FileBody;
  16. import org.apache.http.impl.client.CloseableHttpClient;
  17. import org.apache.http.impl.client.DefaultHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.message.BasicNameValuePair;
  20. import javax.net.ssl.*;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.net.URISyntaxException;
  24. import java.security.KeyManagementException;
  25. import java.security.KeyStoreException;
  26. import java.security.NoSuchAlgorithmException;
  27. import java.security.cert.CertificateException;
  28. import java.security.cert.X509Certificate;
  29. import java.util.LinkedList;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Set;
  33. @SuppressWarnings("deprecation")
  34. public class HttpsUtil extends DefaultHttpClient {
  35. public final static String HTTPGET = "GET";
  36. public final static String HTTPPUT = "PUT";
  37. public final static String HTTPPOST = "POST";
  38. public final static String HTTPDELETE = "DELETE";
  39. public final static String HTTPACCEPT = "Accept";
  40. public final static String CONTENT_LENGTH = "Content-Length";
  41. public final static String CHARSET_UTF8 = "UTF-8";
  42. private static CloseableHttpClient httpClient = getHttpClient();
  43. public static CloseableHttpClient getHttpClient() {
  44. SSLContext sslcontext = null;
  45. try {
  46. sslcontext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
  47. @Override
  48. public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
  49. return true;
  50. }
  51. }).build();
  52. } catch (KeyManagementException e) {
  53. return null;
  54. } catch (NoSuchAlgorithmException e) {
  55. return null;
  56. } catch (KeyStoreException e) {
  57. return null;
  58. }
  59. // Allow TLSv1, TLSv1.1, TLSv1.2 protocol only
  60. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
  61. new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null,
  62. SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  63. CloseableHttpClient httpclient = HttpClients.custom()
  64. .setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(false).build())
  65. .setSSLSocketFactory(sslsf).build();
  66. return httpclient;
  67. }
  68. public HostnameVerifier hv = new HostnameVerifier() {
  69. public boolean verify(String urlHostName, SSLSession session) {
  70. return true;
  71. }
  72. };
  73. public void trustAllHttpsCertificates() throws Exception {
  74. TrustManager[] trustAllCerts = new TrustManager[1];
  75. TrustManager tm = new miTM();
  76. trustAllCerts[0] = tm;
  77. SSLContext sc = SSLContext.getInstance("SSL");
  78. sc.init(null, trustAllCerts, null);
  79. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  80. }
  81. static class miTM implements TrustManager, X509TrustManager {
  82. public X509Certificate[] getAcceptedIssuers() {
  83. return null;
  84. }
  85. public boolean isServerTrusted(X509Certificate[] certs) {
  86. return true;
  87. }
  88. public boolean isClientTrusted(X509Certificate[] certs) {
  89. return true;
  90. }
  91. public void checkServerTrusted(X509Certificate[] certs, String authType)
  92. throws CertificateException {
  93. return;
  94. }
  95. public void checkClientTrusted(X509Certificate[] certs, String authType)
  96. throws CertificateException {
  97. return;
  98. }
  99. }
  100. public HttpResponse doPostJson(String url, Map<String, String> headerMap, String content) {
  101. HttpPost request = new HttpPost(url);
  102. addRequestHeader(request, headerMap);
  103. request.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
  104. return executeHttpRequest(request);
  105. }
  106. public StreamClosedHttpResponse doPostMultipartFile(String url, Map<String, String> headerMap, File file) {
  107. HttpPost request = new HttpPost(url);
  108. addRequestHeader(request, headerMap);
  109. FileBody fileBody = new FileBody(file);
  110. // Content-Type:multipart/form-data;
  111. // boundary=----WebKitFormBoundarypJTQXMOZ3dLEzJ4b
  112. HttpEntity reqEntity = (HttpEntity) MultipartEntityBuilder.create().addPart("file", fileBody).build();
  113. request.setEntity(reqEntity);
  114. return (StreamClosedHttpResponse) executeHttpRequest(request);
  115. }
  116. public StreamClosedHttpResponse doPostJsonGetStatusLine(String url, Map<String, String> headerMap, String content) {
  117. HttpPost request = new HttpPost(url);
  118. addRequestHeader(request, headerMap);
  119. request.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
  120. HttpResponse response = executeHttpRequest(request);
  121. if (null == response) {
  122. System.out.println("The response body is null.");
  123. }
  124. return (StreamClosedHttpResponse) response;
  125. }
  126. public StreamClosedHttpResponse doPostJsonGetStatusLine(String url, String content) {
  127. HttpPost request = new HttpPost(url);
  128. request.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
  129. HttpResponse response = executeHttpRequest(request);
  130. if (null == response) {
  131. System.out.println("The response body is null.");
  132. }
  133. return (StreamClosedHttpResponse) response;
  134. }
  135. public List<NameValuePair> paramsConverter(Map<String, Object> params) {
  136. List<NameValuePair> nvps = new LinkedList<NameValuePair>();
  137. Set<Map.Entry<String, Object>> paramsSet = params.entrySet();
  138. for (Map.Entry<String, Object> paramEntry : paramsSet) {
  139. nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue().toString()));
  140. }
  141. return nvps;
  142. }
  143. public StreamClosedHttpResponse doPostFormUrlEncodedGetStatusLine(String url) throws Exception {
  144. HttpPost request = new HttpPost(url);
  145. HttpResponse response = executeHttpRequest(request);
  146. if (null == response) {
  147. System.out.println("The response body is null.");
  148. throw new Exception();
  149. }
  150. return (StreamClosedHttpResponse) response;
  151. }
  152. public StreamClosedHttpResponse doPostFormUrlEncodedGetStatusLine(String url, Map<String, String> headerMap)
  153. throws Exception {
  154. HttpPost request = new HttpPost(url);
  155. addRequestHeader(request, headerMap);
  156. HttpResponse response = executeHttpRequest(request);
  157. if (null == response) {
  158. System.out.println("The response body is null.");
  159. throw new Exception();
  160. }
  161. return (StreamClosedHttpResponse) response;
  162. }
  163. public StreamClosedHttpResponse doPostFormUrlEncodedGetStatusLine(String url, List<NameValuePair> formParams)
  164. throws Exception {
  165. HttpPost request = new HttpPost(url);
  166. request.setEntity(new UrlEncodedFormEntity(formParams));
  167. HttpResponse response = executeHttpRequest(request);
  168. if (null == response) {
  169. System.out.println("The response body is null.");
  170. throw new Exception();
  171. }
  172. return (StreamClosedHttpResponse) response;
  173. }
  174. public StreamClosedHttpResponse doPostFormUrlEncodedGetStatusLine(String url, Map<String, String> headerMap,
  175. List<NameValuePair> formParams) throws Exception {
  176. HttpPost request = new HttpPost(url);
  177. addRequestHeader(request, headerMap);
  178. request.setEntity(new UrlEncodedFormEntity(formParams));
  179. HttpResponse response = executeHttpRequest(request);
  180. if (null == response) {
  181. System.out.println("The response body is null.");
  182. throw new Exception();
  183. }
  184. return (StreamClosedHttpResponse) response;
  185. }
  186. public HttpResponse doPutJson(String url, Map<String, String> headerMap, String content) {
  187. HttpPut request = new HttpPut(url);
  188. addRequestHeader(request, headerMap);
  189. request.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
  190. return executeHttpRequest(request);
  191. }
  192. public HttpResponse doPut(String url, Map<String, String> headerMap) {
  193. HttpPut request = new HttpPut(url);
  194. addRequestHeader(request, headerMap);
  195. return executeHttpRequest(request);
  196. }
  197. public StreamClosedHttpResponse doPutJsonGetStatusLine(String url, Map<String, String> headerMap, String content) {
  198. HttpResponse response = doPutJson(url, headerMap, content);
  199. if (null == response) {
  200. System.out.println("The response body is null.");
  201. }
  202. return (StreamClosedHttpResponse) response;
  203. }
  204. public StreamClosedHttpResponse doPutGetStatusLine(String url, Map<String, String> headerMap) {
  205. HttpResponse response = doPut(url, headerMap);
  206. if (null == response) {
  207. System.out.println("The response body is null.");
  208. }
  209. return (StreamClosedHttpResponse) response;
  210. }
  211. public HttpResponse doGetWithParas(String url, List<NameValuePair> queryParams, Map<String, String> headerMap)
  212. throws Exception {
  213. HttpGet request = new HttpGet();
  214. addRequestHeader(request, headerMap);
  215. URIBuilder builder;
  216. try {
  217. builder = new URIBuilder(url);
  218. } catch (URISyntaxException e) {
  219. System.out.printf("URISyntaxException: {}", e);
  220. throw new Exception(e);
  221. }
  222. if (queryParams != null && !queryParams.isEmpty()) {
  223. builder.setParameters(queryParams);
  224. }
  225. request.setURI(builder.build());
  226. return executeHttpRequest(request);
  227. }
  228. public StreamClosedHttpResponse doGetWithParasGetStatusLine(String url, List<NameValuePair> queryParams,
  229. Map<String, String> headerMap) throws Exception {
  230. HttpResponse response = doGetWithParas(url, queryParams, headerMap);
  231. if (null == response) {
  232. System.out.println("The response body is null.");
  233. }
  234. return (StreamClosedHttpResponse) response;
  235. }
  236. public HttpResponse doDelete(String url, Map<String, String> headerMap) {
  237. HttpDelete request = new HttpDelete(url);
  238. addRequestHeader(request, headerMap);
  239. return executeHttpRequest(request);
  240. }
  241. public StreamClosedHttpResponse doDeleteGetStatusLine(String url, Map<String, String> headerMap) {
  242. HttpResponse response = doDelete(url, headerMap);
  243. if (null == response) {
  244. System.out.println("The response body is null.");
  245. }
  246. return (StreamClosedHttpResponse) response;
  247. }
  248. private static void addRequestHeader(HttpUriRequest request, Map<String, String> headerMap) {
  249. if (headerMap == null) {
  250. return;
  251. }
  252. for (String headerName : headerMap.keySet()) {
  253. if (CONTENT_LENGTH.equalsIgnoreCase(headerName)) {
  254. continue;
  255. }
  256. String headerValue = headerMap.get(headerName);
  257. request.addHeader(headerName, headerValue);
  258. }
  259. }
  260. private HttpResponse executeHttpRequest(HttpUriRequest request) {
  261. HttpResponse response = null;
  262. try {
  263. response = httpClient.execute(request);
  264. } catch (Exception e) {
  265. System.out.println("executeHttpRequest failed.");
  266. System.out.println(e.getStackTrace());
  267. } finally {
  268. try {
  269. response = new StreamClosedHttpResponse(response);
  270. } catch (IOException e) {
  271. System.out.println("IOException: " + e.getMessage());
  272. }
  273. }
  274. return response;
  275. }
  276. public String getHttpResponseBody(HttpResponse response) throws UnsupportedOperationException, IOException {
  277. if (response == null) {
  278. return null;
  279. }
  280. String body = null;
  281. if (response instanceof StreamClosedHttpResponse) {
  282. body = ((StreamClosedHttpResponse) response).getContent();
  283. } else {
  284. HttpEntity entity = response.getEntity();
  285. if (entity != null && entity.isStreaming()) {
  286. String encoding = entity.getContentEncoding() != null ? entity.getContentEncoding().getValue() : null;
  287. body = StreamUtil.inputStream2String(entity.getContent(), encoding);
  288. }
  289. }
  290. return body;
  291. }
  292. }