HttpClient.java 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. *
  3. * Licensed Property to Sand Co., Ltd.
  4. *
  5. * (C) Copyright of Sand Co., Ltd. 2010
  6. * All Rights Reserved.
  7. *
  8. *
  9. * Modification History:
  10. * =============================================================================
  11. * Author Date Description
  12. * ------------ ---------- ---------------------------------------------------
  13. * 企业产品团队 2016-10-12 Http通讯工具类.
  14. * =============================================================================
  15. */
  16. package cn.com.sandpay.cashier.sdk;
  17. import org.apache.commons.lang.StringUtils;
  18. import org.apache.http.HttpHost;
  19. import org.apache.http.HttpResponse;
  20. import org.apache.http.NameValuePair;
  21. import org.apache.http.client.ClientProtocolException;
  22. import org.apache.http.client.ResponseHandler;
  23. import org.apache.http.client.config.RequestConfig;
  24. import org.apache.http.client.methods.HttpGet;
  25. import org.apache.http.client.methods.HttpPost;
  26. import org.apache.http.client.utils.URLEncodedUtils;
  27. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  28. import org.apache.http.entity.StringEntity;
  29. import org.apache.http.impl.client.CloseableHttpClient;
  30. import org.apache.http.impl.client.HttpClients;
  31. import org.apache.http.message.BasicNameValuePair;
  32. import org.apache.http.util.EntityUtils;
  33. import org.slf4j.Logger;
  34. import org.slf4j.LoggerFactory;
  35. import javax.net.ssl.*;
  36. import java.io.IOException;
  37. import java.net.URL;
  38. import java.security.SecureRandom;
  39. import java.security.cert.CertificateException;
  40. import java.security.cert.X509Certificate;
  41. import java.util.*;
  42. import java.util.Map.Entry;
  43. /**
  44. * @ClassName: HttpClient
  45. * @Description: 主要用于Http通讯
  46. * @version 2.0.0
  47. */
  48. public class HttpClient {
  49. private static Logger logger = LoggerFactory.getLogger(HttpClient.class);
  50. private static final String DEFAULT_CHARSET = "UTF-8";
  51. private static SSLContext sslcontext;
  52. private static SSLConnectionSocketFactory sslsf;
  53. public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout)
  54. throws IOException {
  55. return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
  56. }
  57. public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout,
  58. int readTimeout) throws IOException {
  59. Map<String, String> headers = new HashMap<String, String>();
  60. headers.put("Content-type", "application/x-www-form-urlencoded;charset=" + charset);
  61. return doPost(url, headers, params, charset, connectTimeout, readTimeout);
  62. }
  63. public static String doPost(String url, Map<String, String> headers, Map<String, String> params,
  64. final String charset, int connectTimeout, int readTimeout) throws IOException {
  65. URL targetUrl = new URL(url);
  66. HttpHost httpHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());
  67. logger.info("host:" + targetUrl.getHost() + ",port:" + targetUrl.getPort() + ",protocol:"
  68. + targetUrl.getProtocol() + ",path:" + targetUrl.getPath());
  69. CloseableHttpClient httpclient = getHttpClient(targetUrl);
  70. try {
  71. HttpPost httpPost = getHttpPost(targetUrl, headers, params, charset, connectTimeout, readTimeout);
  72. String resp = httpclient.execute(httpHost, httpPost, new ResponseHandler<String>() {
  73. public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  74. int status = response.getStatusLine().getStatusCode();
  75. logger.info("status:["+status+"]");
  76. if (status == 200) {
  77. return EntityUtils.toString(response.getEntity(), charset);
  78. } else {
  79. return "";
  80. }
  81. }
  82. });
  83. return resp;
  84. } finally {
  85. httpclient.close();
  86. }
  87. }
  88. /**
  89. * 执行HTTP GET请求。
  90. *
  91. * @param url
  92. * 请求地址
  93. * @param params
  94. * 请求参数
  95. * @return 响应字符串
  96. * @throws IOException
  97. */
  98. public static String doGet(String url, Map<String, String> params) throws IOException {
  99. return doGet(url, params, DEFAULT_CHARSET);
  100. }
  101. /**
  102. * 执行HTTP GET请求。
  103. *
  104. * @param url
  105. * 请求地址
  106. * @param params
  107. * 请求参数
  108. * @param charset
  109. * 字符集,如UTF-8, GBK, GB2312
  110. * @return 响应字符串
  111. * @throws IOException
  112. */
  113. public static String doGet(String url, Map<String, String> params, String charset) throws IOException {
  114. Map<String, String> headers = new HashMap<String, String>();
  115. headers.put("Content-type", "application/x-www-form-urlencoded;charset=" + charset);
  116. return doGet(url, headers, params, charset);
  117. }
  118. /**
  119. *
  120. * @param url
  121. * @param headers
  122. * @param params
  123. * @param charset
  124. * @return
  125. * @throws IOException
  126. * @throws ClientProtocolException
  127. */
  128. public static String doGet(String url, Map<String, String> headers, Map<String, String> params,
  129. final String charset) throws IOException {
  130. URL targetUrl = new URL(url);
  131. CloseableHttpClient httpclient = getHttpClient(targetUrl);
  132. try {
  133. HttpGet httpGet = getHttpGet(url, headers, params, charset);
  134. String resp = httpclient.execute(httpGet, new ResponseHandler<String>() {
  135. public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  136. int status = response.getStatusLine().getStatusCode();
  137. logger.info("status:[{}]", new Object[] { status });
  138. if (status == 200) {
  139. return EntityUtils.toString(response.getEntity(), charset);
  140. } else {
  141. return "";
  142. }
  143. }
  144. });
  145. return resp;
  146. } finally {
  147. httpclient.close();
  148. }
  149. }
  150. /**
  151. *
  152. * @param targetUrl
  153. * @param headers
  154. * @param params
  155. * @param charset
  156. * @param isProxy
  157. * @return
  158. * @throws IOException
  159. */
  160. private static HttpGet getHttpGet(String url, Map<String, String> headers, Map<String, String> params,
  161. String charset) throws IOException {
  162. URL targetUrl = buildGetUrl(url, buildQuery(params, charset));
  163. HttpGet httpGet = new HttpGet(targetUrl.toString());
  164. Iterator<Entry<String, String>> iterator = headers.entrySet().iterator();
  165. while (iterator.hasNext()) {
  166. Entry<String, String> entry = iterator.next();
  167. httpGet.setHeader(entry.getKey(), entry.getValue());
  168. }
  169. return httpGet;
  170. }
  171. /**
  172. * @param isProxy
  173. *
  174. * @param targetUrl @param headers @param params @param charset @param
  175. * connectTimeout @param readTimeout @return @throws IOException @throws
  176. */
  177. private static HttpPost getHttpPost(URL targetUrl, Map<String, String> headers, Map<String, String> params,
  178. String charset, int connectTimeout, int readTimeout) throws IOException {
  179. HttpPost httpPost = new HttpPost(targetUrl.getPath());
  180. Iterator<Entry<String, String>> iterator = headers.entrySet().iterator();
  181. while (iterator.hasNext()) {
  182. Entry<String, String> entry = iterator.next();
  183. httpPost.setHeader(entry.getKey(), entry.getValue());
  184. }
  185. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
  186. .setConnectTimeout(connectTimeout) // Connection timeout is the timeout until a connection with the
  187. // server is established.
  188. .build();
  189. httpPost.setConfig(requestConfig);
  190. StringEntity entity = new StringEntity(buildQuery(params, charset), charset);
  191. httpPost.setEntity(entity);
  192. return httpPost;
  193. }
  194. /**
  195. *
  196. * @param targetUrl
  197. * @return
  198. */
  199. private static CloseableHttpClient getHttpClient(URL targetUrl) {
  200. CloseableHttpClient httpClient = null;
  201. if ("https".equals(targetUrl.getProtocol())) {
  202. httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  203. } else {
  204. httpClient = HttpClients.createDefault();
  205. }
  206. return httpClient;
  207. }
  208. private static class DefaultTrustManager implements X509TrustManager {
  209. public X509Certificate[] getAcceptedIssuers() {
  210. return null;
  211. }
  212. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  213. }
  214. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  215. }
  216. }
  217. static {
  218. try {
  219. sslcontext = SSLContext.getInstance("TLS");
  220. sslcontext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
  221. // Allow TLSv1 protocol only
  222. sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, new HostnameVerifier() {
  223. public boolean verify(String hostname, SSLSession session) {
  224. return true;// 默认认证不通过,进行证书校验。
  225. }
  226. });
  227. // javax.net.ssl.SSLPeerUnverifiedException: Host name '192.168.92.124' does not
  228. // match the certificate subject provided by the peer
  229. // (EMAILADDRESS=lsq1015@qq.com, CN=ipay, OU=CMBC, O=XMCMBC, L=Xiamen,
  230. // ST=Fujian, C=CN)
  231. // at
  232. // org.apache.http.conn.ssl.SSLConnectionSocketFactory.verifyHostname(SSLConnectionSocketFactory.java:394)
  233. } catch (Exception e) {
  234. e.printStackTrace();
  235. }
  236. }
  237. public static String buildQuery(Map<String, String> params, String charset) throws IOException {
  238. List<NameValuePair> nvps = new LinkedList<NameValuePair>();
  239. Set<Entry<String, String>> entries = params.entrySet();
  240. for (Entry<String, String> entry : entries) {
  241. nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  242. }
  243. String str = URLEncodedUtils.format(nvps, charset);
  244. return str;
  245. }
  246. public static URL buildGetUrl(String strUrl, String query) throws IOException {
  247. URL url = new URL(strUrl);
  248. if (StringUtils.isEmpty(query)) {
  249. return url;
  250. }
  251. if (StringUtils.isEmpty(url.getQuery())) {
  252. if (strUrl.endsWith("?")) {
  253. strUrl = strUrl + query;
  254. } else {
  255. strUrl = strUrl + "?" + query;
  256. }
  257. } else {
  258. if (strUrl.endsWith("&")) {
  259. strUrl = strUrl + query;
  260. } else {
  261. strUrl = strUrl + "&" + query;
  262. }
  263. }
  264. return new URL(strUrl);
  265. }
  266. }