1. /*
  2. *
  3. *
  4. * FileName: s.java
  5. *
  6. * Description:TODO(用一句话描述该文件做什么)
  7. *
  8. * Created: jiangzhanghong 2017年11月14日
  9. *
  10. * |--------------------------------------------------History---------------------------------------------------|
  11. * | |
  12. * |-----Author-----------|-------Date-------|----Version----|----------------------------Desc----------------------------|
  13. * | jiangzhanghong | 2017年11月14日 | 1.0 | Create
  14. * |------------------------------------------------------------------------------------------------------------|
  15. */
  16. package com.dinfo.app.basic.util;
  17.  
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileNotFoundException;
  21. /**
  22. *
  23. * @author <a href="mailto:jiangzhanghong1@ultrapower.com.cn">jiangzhanghong</a>
  24. * @version 1.0
  25. * @date 2017年11月14日
  26. */
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.OutputStream;
  30. import java.io.UnsupportedEncodingException;
  31. import java.net.HttpURLConnection;
  32. import java.net.MalformedURLException;
  33. import java.net.ProtocolException;
  34. import java.net.URL;
  35. import java.nio.charset.UnsupportedCharsetException;
  36. import java.security.KeyManagementException;
  37. import java.security.NoSuchAlgorithmException;
  38. import java.security.cert.CertificateException;
  39. import java.security.cert.X509Certificate;
  40. import java.util.ArrayList;
  41. import java.util.HashMap;
  42. import java.util.List;
  43. import java.util.Map;
  44.  
  45. import javax.net.ssl.SSLContext;
  46. import javax.net.ssl.SSLException;
  47. import javax.net.ssl.SSLSession;
  48. import javax.net.ssl.SSLSocket;
  49. import javax.net.ssl.TrustManager;
  50. import javax.net.ssl.X509TrustManager;
  51.  
  52. import org.apache.http.Consts;
  53. import org.apache.http.HttpEntity;
  54. import org.apache.http.HttpResponse;
  55. import org.apache.http.HttpStatus;
  56. import org.apache.http.NameValuePair;
  57. import org.apache.http.client.ClientProtocolException;
  58. import org.apache.http.client.config.RequestConfig;
  59. import org.apache.http.client.entity.UrlEncodedFormEntity;
  60. import org.apache.http.client.methods.CloseableHttpResponse;
  61. import org.apache.http.client.methods.HttpGet;
  62. import org.apache.http.client.methods.HttpPost;
  63. import org.apache.http.client.methods.HttpRequestBase;
  64. import org.apache.http.client.utils.URLEncodedUtils;
  65. import org.apache.http.conn.scheme.Scheme;
  66. import org.apache.http.conn.ssl.SSLSocketFactory;
  67. import org.apache.http.conn.ssl.X509HostnameVerifier;
  68. import org.apache.http.entity.ContentType;
  69. import org.apache.http.entity.StringEntity;
  70. import org.apache.http.entity.mime.HttpMultipartMode;
  71. import org.apache.http.entity.mime.MultipartEntityBuilder;
  72. import org.apache.http.impl.client.CloseableHttpClient;
  73. import org.apache.http.impl.client.HttpClients;
  74. import org.apache.http.message.BasicHeader;
  75. import org.apache.http.message.BasicNameValuePair;
  76. import org.apache.http.protocol.HTTP;
  77. import org.apache.http.util.CharsetUtils;
  78. import org.apache.http.util.EntityUtils;
  79. import org.slf4j.Logger;
  80. import org.slf4j.LoggerFactory;
  81. import org.springframework.beans.factory.annotation.Value;
  82. import org.springframework.stereotype.Component;
  83.  
  84. /**
  85. * 封装了一些采用HttpClient发送HTTP请求的方法
  86. *
  87. * @see 本工具所采用的是最新的HttpComponents-Client-4.2.1
  88. */
  89. @Component
  90. public class HttpClientUtil {
  91. private HttpClientUtil() {
  92. }
  93.  
  94. private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
  95.  
  96. private static int connectTimeout=6000;
  97. private static int socketTimeout=60000;
  98. private static int connectionRequestTimeout=6000;
  99.  
  100. public static void main(String[] args) {
  101. try {
  102. System.out.println(HttpClientUtil.sendGetRequest("http://baidu.com", null));
  103. } catch (Exception e) {
  104. // TODO Auto-generated catch block
  105. e.printStackTrace();
  106. }
  107. }
  108.  
  109. /**
  110. * @param connectTimeout the connectTimeout to set
  111. */
  112. @Value("${httpclient.connectTimeout:6000}")
  113. public void setConnectTimeout(int connectTimeout) {
  114. HttpClientUtil.connectTimeout = connectTimeout;
  115. }
  116. /**
  117. * @param socketTimeout the socketTimeout to set
  118. */
  119. @Value("${httpclient.socketTimeout:60000}")
  120. public void setSocketTimeout(int socketTimeout) {
  121. HttpClientUtil.socketTimeout = socketTimeout;
  122. }
  123. /**
  124. * @param connectionRequestTimeout the connectionRequestTimeout to set
  125. */
  126. @Value("${httpclient.connectionRequestTimeout:6000}")
  127. public void setConnectionRequestTimeout(int connectionRequestTimeout) {
  128. HttpClientUtil.connectionRequestTimeout = connectionRequestTimeout;
  129. }
  130. /**
  131. * 发送HTTP_GET请求
  132. *
  133. * @see 该方法会自动关闭连接,释放资源
  134. * @param requestURL
  135. * 请求地址(含参数)
  136. * @param decodeCharset
  137. * 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
  138. * @return 远程主机响应正文
  139. * @throws IOException
  140. * @throws ClientProtocolException
  141. */
  142. public static String sendGetRequest(String reqURL, String decodeCharset) throws ClientProtocolException, IOException {
  143. long responseLength = 0; // 响应长度
  144. String responseContent = null; // 响应内容
  145. CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建默认的httpClient实例
  146. HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet
  147. //设置超时
  148. setTimeout(httpGet);
  149. httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); //解决get请求响应返回中文乱码问题
  150. try {
  151. HttpResponse response = httpClient.execute(httpGet); // 执行GET请求
  152. HttpEntity entity = response.getEntity(); // 获取响应实体
  153. if (null != entity) {
  154. responseLength = entity.getContentLength();
  155. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  156. EntityUtils.consume(entity); // Consume response content
  157. }
  158. System.out.println("请求地址: " + httpGet.getURI());
  159. System.out.println("响应状态: " + response.getStatusLine());
  160. System.out.println("响应长度: " + responseLength);
  161. System.out.println("响应内容: " + responseContent);
  162. } finally {
  163. httpClient.close();
  164. }
  165. return responseContent;
  166. }
  167. /**
  168. * ConnectTimeout 连接建立时间,三次握手完成时间
  169. * SocketTimeout 数据传输过程中数据包之间间隔的最大时间
  170. * ConnectionRequestTimeout httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间
  171. * @param base
  172. */
  173.  
  174. private static void setTimeout(HttpRequestBase base){
  175. RequestConfig requestConfig = RequestConfig.custom()
  176. .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
  177. .setSocketTimeout(socketTimeout).build();
  178. base.setConfig(requestConfig);
  179. }
  180. /**
  181. * 发送HTTP_POST请求
  182. *
  183. * @see 该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法
  184. * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
  185. * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][
  186. * ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
  187. * @param isEncoder
  188. * 用于指明请求数据是否需要UTF-8编码,true为需要
  189. * @throws IOException
  190. * @throws ClientProtocolException
  191. */
  192. public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) throws ClientProtocolException, IOException {
  193. return sendPostRequest(reqURL, sendData, isEncoder, null, null);
  194. }
  195.  
  196. /**
  197. * 发送HTTP_POST请求
  198. *
  199. * @see 该方法会自动关闭连接,释放资源
  200. * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][
  201. * ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
  202. * @param reqURL
  203. * 请求地址
  204. * @param sendData
  205. * 请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中
  206. * @param isEncoder
  207. * 请求数据是否需要encodeCharset编码,true为需要
  208. * @param encodeCharset
  209. * 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
  210. * @param decodeCharset
  211. * 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
  212. * @return 远程主机响应正文
  213. * @throws IOException
  214. * @throws ClientProtocolException
  215. */
  216. public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset,
  217. String decodeCharset) throws ClientProtocolException, IOException {
  218. String responseContent = null;
  219. CloseableHttpClient httpClient = HttpClients.createDefault();
  220.  
  221. HttpPost httpPost = new HttpPost(reqURL);
  222. //设置超时
  223. setTimeout(httpPost);
  224. httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
  225. try {
  226. if (isEncoder) {
  227. List<NameValuePair> formParams = new ArrayList<NameValuePair>();
  228. for (String str : sendData.split("&")) {
  229. formParams.add(new BasicNameValuePair(str.substring(0, str.indexOf("=")),
  230. str.substring(str.indexOf("=") + 1)));
  231. }
  232. httpPost.setEntity(new StringEntity(
  233. URLEncodedUtils.format(formParams, encodeCharset == null ? "UTF-8" : encodeCharset)));
  234. } else {
  235. httpPost.setEntity(new StringEntity(sendData));
  236. }
  237.  
  238. HttpResponse response = httpClient.execute(httpPost);
  239. HttpEntity entity = response.getEntity();
  240. if (null != entity) {
  241. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  242. EntityUtils.consume(entity);
  243. }
  244. } finally {
  245. httpClient.close();
  246. }
  247. return responseContent;
  248. }
  249.  
  250. /**
  251. * 支持单个文件上传
  252. * @param reqURL 请求url
  253. * @param bytes 传递的二进制内容
  254. * @param fileparm 参数名称
  255. * @param decodeCharset
  256. * @return
  257. * @throws IOException
  258. * @throws ClientProtocolException
  259. * @throws Exception
  260. */
  261. public static String sendPostByte(String reqURL, byte[] bytes, String fileparm,String filename,
  262. String decodeCharset) throws ClientProtocolException, IOException {
  263. String responseContent = null;
  264. CloseableHttpClient httpClient = HttpClients.createDefault();
  265. HttpPost httpPost = new HttpPost(reqURL);
  266. //设置超时
  267. setTimeout(httpPost);
  268. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  269. builder.addBinaryBody(fileparm, bytes, ContentType.create("multipart/form-data","UTF-8"), filename);
  270. HttpEntity multipart = builder.build();
  271. httpPost.setEntity(multipart);
  272. try {
  273. HttpResponse response = httpClient.execute(httpPost);
  274. HttpEntity entity = response.getEntity();
  275. if (null != entity) {
  276. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  277. EntityUtils.consume(entity);
  278. }
  279. } finally {
  280. httpClient.close();
  281. }
  282. return responseContent;
  283. }
  284.  
  285. /**
  286. * 单个文件上传,file方式
  287. * @param reqURL
  288. * @param file
  289. * @param fileparm
  290. * @param decodeCharset
  291. * @return
  292. * @throws UnsupportedCharsetException
  293. * @throws IOException
  294. * @throws ClientProtocolException
  295. * @throws Exception
  296. */
  297. public static String sendPostFile(String reqURL,File file, String fileparm,
  298. String decodeCharset) throws UnsupportedCharsetException, ClientProtocolException, IOException {
  299. String responseContent = null;
  300. CloseableHttpClient httpClient = HttpClients.createDefault();
  301. HttpPost httpPost = new HttpPost(reqURL);
  302. //设置超时
  303. setTimeout(httpPost);
  304. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  305. builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  306. builder.setCharset(CharsetUtils.get("UTF-8")); //设置编码,解决上传文件名乱码问题
  307. builder.addBinaryBody(fileparm, new FileInputStream(file), ContentType.create("multipart/form-data","UTF-8"), file.getName());
  308. HttpEntity multipart = builder.build();
  309. httpPost.setEntity(multipart);
  310. try {
  311. HttpResponse response = httpClient.execute(httpPost);
  312. HttpEntity entity = response.getEntity();
  313. if (null != entity) {
  314. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  315. EntityUtils.consume(entity);
  316. }
  317. } finally {
  318. httpClient.close();
  319. }
  320. return responseContent;
  321. }
  322. public static String sendPostMutipart(String reqURL, List<byte[]> bytes, List<String> fileparams,List<String> fileNames,List<String> paramNames,List<String> paramValues,
  323. String decodeCharset) throws ClientProtocolException, IOException {
  324. String responseContent = null;
  325. CloseableHttpClient httpClient = HttpClients.createDefault();
  326. HttpPost httpPost = new HttpPost(reqURL);
  327. //设置超时
  328. setTimeout(httpPost);
  329. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  330. builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  331. builder.setCharset(CharsetUtils.get("UTF-8"));
  332. for (int i = 0; i < bytes.size(); i++) {
  333.  
  334. builder.addBinaryBody(fileparams.get(i), bytes.get(i), ContentType.create("multipart/form-data","UTF-8"), fileNames.get(i));
  335. }
  336. for (int i = 0; i < paramNames.size(); i++) {
  337. builder.addTextBody(paramNames.get(i), paramValues.get(i), ContentType.create("multipart/form-data","UTF-8"));
  338. }
  339. HttpEntity multipart = builder.build();
  340. httpPost.setEntity(multipart);
  341. try {
  342. HttpResponse response = httpClient.execute(httpPost);
  343. HttpEntity entity = response.getEntity();
  344. if (null != entity) {
  345. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  346. EntityUtils.consume(entity);
  347. }
  348. } finally {
  349. httpClient.close();
  350. }
  351. return responseContent;
  352. }
  353.  
  354. /**
  355. * 发送HTTP_POST请求
  356. *
  357. * @see 该方法会自动关闭连接,释放资源
  358. * @see 该方法会自动对<code>params</code>中的[中文][|][
  359. * ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
  360. * @param reqURL
  361. * 请求地址
  362. * @param params
  363. * 请求参数
  364. * @param encodeCharset
  365. * 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
  366. * @param decodeCharset
  367. * 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
  368. * @return 远程主机响应正文
  369. * @throws IOException
  370. * @throws ClientProtocolException
  371. */
  372. public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset,
  373. String decodeCharset) throws ClientProtocolException, IOException {
  374. String responseContent = null;
  375. CloseableHttpClient httpClient = HttpClients.createDefault();
  376. if(params==null){
  377. params=new HashMap<String, String>();
  378. }
  379. HttpPost httpPost = new HttpPost(reqURL);
  380. //设置超时
  381. //setTimeout(httpPost);
  382. List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数队列
  383. for (Map.Entry<String, String> entry : params.entrySet()) {
  384. formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  385. }
  386. try {
  387. httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset == null ? "UTF-8" : encodeCharset));
  388.  
  389. HttpResponse response = httpClient.execute(httpPost);
  390. HttpEntity entity = response.getEntity();
  391. if (null != entity) {
  392. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  393. EntityUtils.consume(entity);
  394. }
  395. } finally {
  396. httpClient.close();
  397. }
  398. return responseContent;
  399. }
  400.  
  401. /**
  402. * 发送HTTPS_POST请求
  403. * @throws IOException
  404. * @throws ClientProtocolException
  405. * @throws NoSuchAlgorithmException
  406. * @throws KeyManagementException
  407. *
  408. * @see 该方法为<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的简化方法
  409. * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
  410. * @see 该方法会自动对<code>params</code>中的[中文][|][
  411. * ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
  412. */
  413. public static String sendPostSSLRequest(String reqURL, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
  414. return sendPostSSLRequest(reqURL, params, null, null);
  415. }
  416.  
  417. /**
  418. * 发送HTTPS_POST请求
  419. *
  420. * @see 该方法会自动关闭连接,释放资源
  421. * @see 该方法会自动对<code>params</code>中的[中文][|][
  422. * ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
  423. * @param reqURL
  424. * 请求地址
  425. * @param params
  426. * 请求参数
  427. * @param encodeCharset
  428. * 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
  429. * @param decodeCharset
  430. * 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
  431. * @return 远程主机响应正文
  432. * @throws NoSuchAlgorithmException
  433. * @throws KeyManagementException
  434. * @throws IOException
  435. * @throws ClientProtocolException
  436. */
  437. public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset,
  438. String decodeCharset) throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
  439. String responseContent = "";
  440. CloseableHttpClient httpClient = HttpClients.createDefault();
  441. X509TrustManager xtm = new X509TrustManager() {
  442. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  443. }
  444.  
  445. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  446. }
  447.  
  448. public X509Certificate[] getAcceptedIssuers() {
  449. return null;
  450. }
  451. };
  452. try {
  453. SSLContext ctx = SSLContext.getInstance("TLS");
  454. ctx.init(null, new TrustManager[] { xtm }, null);
  455. SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
  456. httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
  457.  
  458. HttpPost httpPost = new HttpPost(reqURL);
  459. //设置超时
  460. setTimeout(httpPost);
  461. List<NameValuePair> formParams = new ArrayList<NameValuePair>();
  462. for (Map.Entry<String, String> entry : params.entrySet()) {
  463. formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  464. }
  465. httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset == null ? "UTF-8" : encodeCharset));
  466.  
  467. HttpResponse response = httpClient.execute(httpPost);
  468. HttpEntity entity = response.getEntity();
  469. if (null != entity) {
  470. responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
  471. EntityUtils.consume(entity);
  472. }
  473. } finally {
  474. httpClient.close();
  475. }
  476. return responseContent;
  477. }
  478.  
  479. /**
  480. * 发送HTTP_POST请求
  481. *
  482. * @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
  483. * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
  484. * @param reqURL
  485. * 请求地址
  486. * @param params
  487. * 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
  488. * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>
  489. * 若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
  490. * @throws IOException
  491. * @throws Exception
  492. */
  493. public static String sendPostRequestByJava(String reqURL, Map<String, String> params) throws IOException {
  494. StringBuilder sendData = new StringBuilder();
  495. for (Map.Entry<String, String> entry : params.entrySet()) {
  496. sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
  497. }
  498. if (sendData.length() > 0) {
  499. sendData.setLength(sendData.length() - 1); // 删除最后一个&符号
  500. }
  501. return sendPostRequestByJava(reqURL, sendData.toString());
  502. }
  503.  
  504. /**
  505. * 发送HTTP_POST请求
  506. *
  507. * @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
  508. * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
  509. * @param reqURL
  510. * 请求地址
  511. * @param sendData
  512. * 发送到远程主机的正文数据
  513. * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>
  514. * 若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
  515. * @throws IOException
  516. */
  517. public static String sendPostRequestByJava(String reqURL, String sendData) throws IOException {
  518. HttpURLConnection httpURLConnection = null;
  519. OutputStream out = null; // 写
  520. InputStream in = null; // 读
  521. int httpStatusCode = 0; // 远程主机响应的HTTP状态码
  522. try {
  523. URL sendUrl = new URL(reqURL);
  524. httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
  525. httpURLConnection.setRequestMethod("POST");
  526. httpURLConnection.setDoOutput(true); // 指示应用程序要将数据写入URL连接,其值默认为false
  527. httpURLConnection.setUseCaches(false);
  528. httpURLConnection.setConnectTimeout(60000); // 60秒连接超时
  529. httpURLConnection.setReadTimeout(60000); // 60秒读取超时
  530.  
  531. out = httpURLConnection.getOutputStream();
  532. out.write(sendData.toString().getBytes());
  533.  
  534. // 清空缓冲区,发送数据
  535. out.flush();
  536.  
  537. // 获取HTTP状态码
  538. httpStatusCode = httpURLConnection.getResponseCode();
  539.  
  540. in = httpURLConnection.getInputStream();
  541. byte[] byteDatas = new byte[in.available()];
  542. in.read(byteDatas);
  543. return new String(byteDatas) + "`" + httpStatusCode;
  544. } finally {
  545. if (out != null) {
  546. try {
  547. out.close();
  548. } catch (Exception e) {
  549. logger.debug("关闭输出流时发生异常,堆栈信息如下", e);
  550. }
  551. }
  552. if (in != null) {
  553. try {
  554. in.close();
  555. } catch (Exception e) {
  556. logger.debug("关闭输入流时发生异常,堆栈信息如下", e);
  557. }
  558. }
  559. if (httpURLConnection != null) {
  560. httpURLConnection.disconnect();
  561. httpURLConnection = null;
  562. }
  563. }
  564. }
  565.  
  566. /**
  567. * https posp请求,可以绕过证书校验
  568. *
  569. * @param url
  570. * @param params
  571. * @return
  572. * @throws NoSuchAlgorithmException
  573. * @throws KeyManagementException
  574. * @throws IOException
  575. * @throws ClientProtocolException
  576. */
  577. public static final String sendHttpsRequestByPost(String url, Map<String, String> params) throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
  578. String responseContent = null;
  579. CloseableHttpClient httpClient = HttpClients.createDefault();
  580. // 创建TrustManager
  581. X509TrustManager xtm = new X509TrustManager() {
  582. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  583. }
  584.  
  585. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  586. }
  587.  
  588. public X509Certificate[] getAcceptedIssuers() {
  589. return null;
  590. }
  591. };
  592. // 这个好像是HOST验证
  593. X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
  594. public boolean verify(String arg0, SSLSession arg1) {
  595. return true;
  596. }
  597.  
  598. public void verify(String arg0, SSLSocket arg1) throws IOException {
  599. }
  600.  
  601. public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
  602. }
  603.  
  604. public void verify(String arg0, X509Certificate arg1) throws SSLException {
  605. }
  606. };
  607. try {
  608. // TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
  609. SSLContext ctx = SSLContext.getInstance("TLS");
  610. // 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
  611. ctx.init(null, new TrustManager[] { xtm }, null);
  612. // 创建SSLSocketFactory
  613. SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
  614. socketFactory.setHostnameVerifier(hostnameVerifier);
  615. // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
  616. httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
  617. HttpPost httpPost = new HttpPost(url);
  618. //设置超时
  619. setTimeout(httpPost);
  620. List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
  621. for (Map.Entry<String, String> entry : params.entrySet()) {
  622. formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  623. }
  624. httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
  625. HttpResponse response = httpClient.execute(httpPost);
  626. HttpEntity entity = response.getEntity(); // 获取响应实体
  627. if (entity != null) {
  628. responseContent = EntityUtils.toString(entity, "UTF-8");
  629. }
  630. } finally {
  631. // 关闭连接,释放资源
  632. try {
  633. httpClient.close();
  634. } catch (IOException e) {
  635. logger.error(e.getMessage());
  636. }
  637. }
  638. return responseContent;
  639. }
  640.  
  641. /**
  642. * 发送HTTP_POST请求,json格式数据
  643. *
  644. * @param url
  645. * @param body
  646. * @return
  647. * @throws IOException
  648. * @throws ClientProtocolException
  649. * @throws Exception
  650. */
  651. public static String sendPostByJson(String url, String body) throws ClientProtocolException, IOException {
  652. CloseableHttpClient httpclient = HttpClients.custom().build();
  653. HttpPost post = null;
  654. String resData = null;
  655. CloseableHttpResponse result = null;
  656. try {
  657. post = new HttpPost(url);
  658. //设置超时
  659. setTimeout(post);
  660. HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
  661. post.setConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
  662. post.setHeader("Content-Type", "application/json");
  663. post.setEntity(entity2);
  664. result = httpclient.execute(post);
  665. if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
  666. resData = EntityUtils.toString(result.getEntity());
  667. }
  668. } finally {
  669. if (result != null) {
  670. result.close();
  671. }
  672. if (post != null) {
  673. post.releaseConnection();
  674. }
  675. httpclient.close();
  676. }
  677. return resData;
  678. }
  679.  
  680. }

HttpClientUtil 工具类的更多相关文章

  1. HttpClientUtil工具类,待更新

    package com.igs.webShop.web.util; import org.apache.http.HttpEntity;import org.apache.http.HttpRespo ...

  2. 通用HttpClientUtil工具类

    package com.*.utils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; im ...

  3. HttpClientUtil 工具类 实现跨域请求数据

    package com.xxx.common.util; import java.io.IOException; import java.net.URI; import java.util.Array ...

  4. HttpClientUtil工具类封装

    package com.jd.ng.shiro.utils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; ...

  5. 轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求

    近期更新了一下HttpClientUtil工具类代码,主要是加入了一个參数HttpContext,这个是用来干嘛的呢?事实上是用来保存和传递Cookie所须要的. 由于我们有非常多时候都须要登录.然后 ...

  6. 基于HttpClient4.5.2实现的HttpClient工具类

    1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...

  7. 带有连接池的Http客户端工具类HttpClientUtil

    一.背景 业务开发中,经常会遇到通过http/https向下游服务发送请求.每次都要重复造轮子写HttpClient的逻辑,而且性能.功能参差不齐.这里分享一个高性能的.带连接池的通用Http客户端工 ...

  8. HttpClient 4.5.x 工具类设计与实现

    最近,业务需要在java服务端发起http请求,需要实现"GET","POST","PUT"等基本方法.于是想以 "HttpCli ...

  9. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

随机推荐

  1. TFS撤销其他人的迁出

    1.cd C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE 2.查看工作区tf workspaces /owner:zho ...

  2. [原]System.IO.Path.Combine 路径合并

    使用 ILSpy 工具查看了 System.IO.Path 类中的 Combine 方法 对它的功能有点不放心,原方法实现如下: // System.IO.Path /// <summary&g ...

  3. 3-4 1449 web view

    1.app类型 不同类型的应用 区别 native app 纯原声app,Android用Java些,iOS用object c写 hybrid app 套用原声应用的外壳,既有原生的UI页面,又通过内 ...

  4. js用法

    属性(attribute) function fn(){ console.log(123) } fn() var a=fn()                 将函数fn()调用结果赋值给a 1.函数 ...

  5. docker 基础操作

    1. 安装docker 系统centos 7.2 yum -y install docker-io service docker start 安装完毕后执行 docker version 或者dock ...

  6. Linux下安装Nginx依赖包和Nginx的命令

    1.安装依赖包pcrecd /usr/local/srcwget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.39.tar ...

  7. Docker集群管理(一)—— 基础docker+swarm+shipyard

    目的 学习docker的集群管理,摸索出高可用的docker微服务架构方案.本篇文章只初步的了解下swarm(docker新版已集成了swarm)的使用,了解docker的发现服务的基础方法(dock ...

  8. Django中间件执行流程

    中间件函数是 django 框架为我们预留的函数接口, 让我们可以干预请求和应答的过程 1. 获取浏览器端的IP地址: 使用 request.META[‘REMOTE_ADDR’] 2. 使用中间件 ...

  9. IO流程及优化

    http://blog.csdn.net/xypzwl/article/details/51416883 一.存储设备的存储原理 机械硬盘: 机械硬盘使用磁性物质作为存储介质,用N.S极性来代表0或1 ...

  10. solr入门之搜索建议的几种实现方式和最终选取实现思路

    上篇博客中我简单的讲了下solr自身的suggest模块来实现搜索建议.但是今天研究了下在solr自身的suggest中添加进去拼音来智能推荐时不时很方便.在次从网上搜集和整理思考了下该问题的解决. ...