HttpTemplete.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package com.huimv.business.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.http.HttpEntity;
  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.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.message.BasicNameValuePair;
  11. import org.apache.http.util.EntityUtils;
  12. import org.springframework.stereotype.Component;
  13. import java.io.IOException;
  14. import java.util.*;
  15. /**
  16. * @Project : huimv.shiwan
  17. * @Package : com.huimv.biosafety.uface.controller
  18. * @Description : TODO
  19. * @Version : 1.0
  20. * @Author : ZhuoNing
  21. * @Create : 2020-12-25
  22. **/
  23. @Component
  24. public class HttpTemplete {
  25. private String testHttpIp = "http://localhost:9105";
  26. // public static void main(String[] args) throws Exception {
  27. // //
  28. // HttpTemplete client = new HttpTemplete();
  29. //// client.testGetRequest1();
  30. // client.testGetRequest2();
  31. // }
  32. private Integer connectTimeout = null;
  33. private Integer requestTimeout = null;
  34. private Integer socketTimeout = null;
  35. static {
  36. }
  37. //发送简单数据
  38. public void doPostSimple(String serviceUrl,String data){
  39. System.out.println("推送数据地址:"+serviceUrl);
  40. //
  41. Map<String,String> paramsMap = new HashMap<String,String>();
  42. paramsMap.put("data", data);
  43. //
  44. Map<String,Integer> timeoutMap = new HashMap<String,Integer>();
  45. timeoutMap.put("connectTimeout", 5000);
  46. timeoutMap.put("requestTimeout", 5000);
  47. timeoutMap.put("socketTimeout", 5000);
  48. try{
  49. // 用Post方法推送接口数据
  50. doPost(serviceUrl,paramsMap,timeoutMap);
  51. } catch (IOException e) {
  52. System.out.println("###错误信息:"+e.getMessage());
  53. }
  54. }
  55. /**
  56. * @Method : doPost
  57. * @Description : post方式推送接口
  58. * @Params : [url, paramsMap, timeoutMap]
  59. * @Return : com.alibaba.fastjson.JSONObject
  60. *
  61. * @Author : ZhuoNing
  62. * @Date : 2021/11/19
  63. * @Time : 14:55
  64. */
  65. public JSONObject doPost(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
  66. // 创建默认的httpClient实例.
  67. CloseableHttpClient httpClient = getHttpClientConnection();
  68. //
  69. int connectTimeout = timeoutMap.get("connectTimeout");
  70. int requestTimeout = timeoutMap.get("requestTimeout");
  71. int socketTimeout = timeoutMap.get("socketTimeout");
  72. // 创建httpPost
  73. HttpPost httpPost = new HttpPost(url);
  74. RequestConfig requestConfig = RequestConfig.custom()
  75. .setSocketTimeout(socketTimeout) //服务器响应超时时间
  76. .setConnectTimeout(connectTimeout) //连接服务器超时时间
  77. .setConnectionRequestTimeout(requestTimeout)
  78. .build();
  79. httpPost.setConfig(requestConfig);
  80. // 创建参数队列
  81. List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
  82. Set<Map.Entry<String, String>> entrySet = paramsMap.entrySet();
  83. for (Map.Entry<String, String> e : entrySet) {
  84. String name = e.getKey();
  85. String value = e.getValue();
  86. NameValuePair pair = new BasicNameValuePair(name, value);
  87. paramsList.add(pair);
  88. }
  89. UrlEncodedFormEntity content = new UrlEncodedFormEntity(paramsList, "UTF-8");
  90. //处理乱码
  91. // StringEntity content = new StringEntity(paramsList.toString(), Charset.forName("UTF-8"));// 第二个参数,设置后才会对,内容进行编码
  92. // content.setContentType("application/soap+xml; charset=UTF-8");
  93. // content.setContentEncoding("UTF-8");
  94. httpPost.setEntity(content);
  95. // HttpUriRequest httpPost = RequestBuilder.post().setUri(url).setEntity(content).setConfig(requestConfig);
  96. CloseableHttpResponse response = httpClient.execute(httpPost);
  97. // 获取响应实体
  98. HttpEntity entity = response.getEntity();
  99. try {
  100. if (response.getStatusLine().getStatusCode() == 200) {
  101. // 打印响应内容
  102. String text = EntityUtils.toString(entity, "utf-8");
  103. JSONObject resultJo = new JSONObject();
  104. resultJo.put("status", true);
  105. resultJo.put("content", text);
  106. return resultJo;
  107. }else{
  108. String text = EntityUtils.toString(entity, "utf-8");
  109. JSONObject resultJo = new JSONObject();
  110. resultJo.put("status", false);
  111. resultJo.put("content", text);
  112. return resultJo;
  113. }
  114. } finally {
  115. //释放资源
  116. if (response != null) {
  117. response.close();
  118. }
  119. if (httpClient != null) {
  120. httpClient.close();
  121. }
  122. }
  123. }
  124. /**
  125. * @Method : setTimeout
  126. * @Description :
  127. * @Params : [connectTimeout, requestTimeout, socketTimeout]
  128. * @Return : void
  129. *
  130. * @Author : ZhuoNing
  131. * @Date : 2021/11/23
  132. * @Time : 9:36
  133. */
  134. public Map<String, Integer> setTimeout(Integer connectTimeout, Integer requestTimeout, Integer socketTimeout){
  135. //
  136. if(connectTimeout == null){
  137. this.connectTimeout = 3000;
  138. }else{
  139. this.connectTimeout = connectTimeout;
  140. }
  141. //
  142. if(requestTimeout == null){
  143. this.requestTimeout = 3000;
  144. }else{
  145. this.requestTimeout = requestTimeout;
  146. }
  147. //
  148. if(socketTimeout == null){
  149. this.socketTimeout = 3000;
  150. }else{
  151. this.socketTimeout = socketTimeout;
  152. }
  153. Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
  154. timeoutMap.put("connectTimeout", this.connectTimeout);
  155. timeoutMap.put("requestTimeout", this.requestTimeout);
  156. timeoutMap.put("socketTimeout", this.socketTimeout);
  157. return timeoutMap;
  158. }
  159. /**
  160. * @Method : setTimeout
  161. * @Description :
  162. * @Params : [connectTimeout, requestTimeout, socketTimeout]
  163. * @Return : java.util.Map<java.lang.String,java.lang.Integer>
  164. *
  165. * @Author : ZhuoNing
  166. * @Date : 2021/11/23
  167. * @Time : 9:41
  168. */
  169. public Map<String, Integer> setTimeout(String connectTimeout, String requestTimeout, String socketTimeout){
  170. //
  171. if(connectTimeout == null){
  172. this.connectTimeout = 3000;
  173. }else{
  174. this.connectTimeout = Integer.parseInt(connectTimeout);
  175. }
  176. //
  177. if(requestTimeout == null){
  178. this.requestTimeout = 3000;
  179. }else{
  180. this.requestTimeout = Integer.parseInt(requestTimeout);
  181. }
  182. //
  183. if(socketTimeout == null){
  184. this.socketTimeout = 3000;
  185. }else{
  186. this.socketTimeout = Integer.parseInt(socketTimeout);
  187. }
  188. Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
  189. timeoutMap.put("connectTimeout", this.connectTimeout);
  190. timeoutMap.put("requestTimeout", this.requestTimeout);
  191. timeoutMap.put("socketTimeout", this.socketTimeout);
  192. return timeoutMap;
  193. }
  194. /**
  195. * @Method : doGet
  196. * @Description :
  197. * @Params : [url, paramsMap]
  198. * @Return : com.alibaba.fastjson.JSONObject
  199. *
  200. * @Author : ZhuoNing
  201. * @Date : 2021/11/23
  202. * @Time : 9:34
  203. */
  204. public JSONObject doGet(String url, Map<String, String> paramsMap) throws IOException {
  205. //
  206. if(this.connectTimeout == null){
  207. this.connectTimeout = 3000;
  208. }
  209. //
  210. if(this.requestTimeout == null)
  211. {
  212. this.requestTimeout = 3000;
  213. }
  214. //
  215. if(this.socketTimeout == null){
  216. this.socketTimeout = 3000;
  217. }
  218. Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
  219. timeoutMap.put("connectTimeout", this.connectTimeout);
  220. timeoutMap.put("requestTimeout", this.requestTimeout);
  221. timeoutMap.put("socketTimeout", this.socketTimeout);
  222. //
  223. CloseableHttpClient httpClient = getHttpClientConnection();
  224. //执行//获取请求内容
  225. CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
  226. try {
  227. // 获取响应实体
  228. HttpEntity entity = response.getEntity();
  229. // 打印响应状态
  230. if (response.getStatusLine().getStatusCode() == 200) {
  231. // 打印响应内容
  232. String text = EntityUtils.toString(entity, "utf-8");
  233. JSONObject resultJo = new JSONObject();
  234. resultJo.put("status", true);
  235. resultJo.put("content", text);
  236. return resultJo;
  237. } else {
  238. String text = EntityUtils.toString(entity, "utf-8");
  239. JSONObject resultJo = new JSONObject();
  240. resultJo.put("status", false);
  241. resultJo.put("content", text);
  242. return resultJo;
  243. }
  244. } finally {
  245. //释放资源
  246. if (response != null) {
  247. response.close();
  248. }
  249. if (httpClient != null) {
  250. httpClient.close();
  251. }
  252. }
  253. }
  254. private CloseableHttpClient httpClient = null;
  255. private CloseableHttpResponse response = null;
  256. public JSONObject doGetBatch(String url, Map<String, String> paramsMap) throws IOException {
  257. //
  258. if(this.connectTimeout == null){
  259. this.connectTimeout = 3000;
  260. }
  261. //
  262. if(this.requestTimeout == null)
  263. {
  264. this.requestTimeout = 3000;
  265. }
  266. //
  267. if(this.socketTimeout == null){
  268. this.socketTimeout = 3000;
  269. }
  270. Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
  271. timeoutMap.put("connectTimeout", this.connectTimeout);
  272. timeoutMap.put("requestTimeout", this.requestTimeout);
  273. timeoutMap.put("socketTimeout", this.socketTimeout);
  274. //
  275. httpClient = getHttpClientConnection();
  276. //执行//获取请求内容
  277. response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
  278. // 获取响应实体
  279. HttpEntity entity = response.getEntity();
  280. // 打印响应状态
  281. if (response.getStatusLine().getStatusCode() == 200) {
  282. // 打印响应内容
  283. String text = EntityUtils.toString(entity, "utf-8");
  284. JSONObject resultJo = new JSONObject();
  285. resultJo.put("status", true);
  286. resultJo.put("content", text);
  287. return resultJo;
  288. } else {
  289. String text = EntityUtils.toString(entity, "utf-8");
  290. JSONObject resultJo = new JSONObject();
  291. resultJo.put("status", false);
  292. resultJo.put("content", text);
  293. return resultJo;
  294. }
  295. }
  296. //关闭http连接
  297. public void closeHttpConn() throws IOException {
  298. System.out.println("开始释放http连接资源");
  299. //释放资源
  300. if (response != null) {
  301. response.close();
  302. }
  303. if (httpClient != null) {
  304. httpClient.close();
  305. }
  306. }
  307. /**
  308. * @Method : doGet
  309. * @Description :get方式推送接口
  310. * @Params : [url, paramsMap, timeoutMap]
  311. * @Return : com.alibaba.fastjson.JSONObject
  312. * @Author : ZhuoNing
  313. * @Date : 2021/11/18
  314. * @Time : 17:39
  315. */
  316. public JSONObject doGet(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
  317. if (timeoutMap == null) {
  318. timeoutMap.put("connectTimeout", 5000);
  319. timeoutMap.put("requestTimeout", 5000);
  320. timeoutMap.put("socketTimeout", 5000);
  321. }
  322. //
  323. CloseableHttpClient httpClient = getHttpClientConnection();
  324. //执行//获取请求内容
  325. CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
  326. try {
  327. // 获取响应实体
  328. HttpEntity entity = response.getEntity();
  329. // 打印响应状态
  330. if (response.getStatusLine().getStatusCode() == 200) {
  331. // 打印响应内容
  332. String text = EntityUtils.toString(entity, "utf-8");
  333. JSONObject resultJo = new JSONObject();
  334. resultJo.put("status", true);
  335. resultJo.put("content", text);
  336. return resultJo;
  337. } else {
  338. String text = EntityUtils.toString(entity, "utf-8");
  339. JSONObject resultJo = new JSONObject();
  340. resultJo.put("status", false);
  341. resultJo.put("content", text);
  342. return resultJo;
  343. }
  344. } finally {
  345. //释放资源
  346. if (response != null) {
  347. response.close();
  348. }
  349. if (httpClient != null) {
  350. httpClient.close();
  351. }
  352. }
  353. }
  354. private void testGetRequest1() throws IOException {
  355. Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
  356. timeoutMap.put("connectTimeout", 5000);
  357. timeoutMap.put("requestTimeout", 5000);
  358. timeoutMap.put("socketTimeout", 5000);
  359. String url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
  360. // test error
  361. url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c&userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
  362. CloseableHttpClient httpClient = getHttpClientConnection();
  363. CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, timeoutMap));
  364. // 打印响应状态
  365. System.out.println("响应状态1 =" + response.getStatusLine());
  366. try {
  367. if (response.getStatusLine().getStatusCode() == 200) {
  368. // 获取响应实体
  369. HttpEntity entity = response.getEntity();
  370. // 打印响应内容
  371. String text = EntityUtils.toString(entity, "utf-8");
  372. System.out.println("响应内容=" + text);
  373. JSONObject resultJo = JSONObject.parseObject(text);
  374. System.out.println("accessToken=" + resultJo.getString("accessToken"));
  375. } else {
  376. System.out.println("请求失败");
  377. }
  378. } finally {
  379. //释放资源
  380. if (response != null) {
  381. response.close();
  382. }
  383. if (httpClient != null) {
  384. httpClient.close();
  385. }
  386. }
  387. }
  388. //
  389. private CloseableHttpClient getHttpClientConnection() {
  390. //创建默认实例
  391. CloseableHttpClient httpclient = HttpClients.createDefault();
  392. //
  393. // CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  394. return httpclient;
  395. }
  396. //
  397. private HttpUriRequest getHttpRequest(String url, Map<String, String> map, Map<String, Integer> timeoutMap) {
  398. int connectTimeout = timeoutMap.get("connectTimeout");
  399. int requestTimeout = timeoutMap.get("requestTimeout");
  400. int socketTimeout = timeoutMap.get("socketTimeout");
  401. // System.out.println("core connectTimeout="+connectTimeout);
  402. // System.out.println("core requestTimeout="+requestTimeout);
  403. // System.out.println("core socketTimeout="+socketTimeout);
  404. List<NameValuePair> params = new ArrayList<NameValuePair>();
  405. Set<Map.Entry<String, String>> entrySet = map.entrySet();
  406. for (Map.Entry<String, String> e : entrySet) {
  407. String name = e.getKey();
  408. String value = e.getValue();
  409. NameValuePair pair = new BasicNameValuePair(name, value);
  410. params.add(pair);
  411. }
  412. //
  413. RequestConfig requestConfig = RequestConfig.custom()
  414. .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
  415. .setSocketTimeout(socketTimeout).build();
  416. HttpUriRequest httpGet = RequestBuilder.get().setUri(url)
  417. .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
  418. .setConfig(requestConfig).build();
  419. return httpGet;
  420. }
  421. //
  422. private HttpGet getHttpRequest(String url, Map<String, Integer> timeoutMap) {
  423. int connectTimeout = timeoutMap.get("connectTimeout");
  424. int requestTimeout = timeoutMap.get("requestTimeout");
  425. int socketTimeout = timeoutMap.get("socketTimeout");
  426. HttpGet httpGet = new HttpGet(url);
  427. //设置超时时间
  428. RequestConfig requestConfig = RequestConfig.custom()
  429. .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
  430. .setSocketTimeout(socketTimeout).build();
  431. httpGet.setConfig(requestConfig);
  432. return httpGet;
  433. }
  434. //test
  435. private void get() {
  436. // CloseableHttpClient httpclient = HttpClients.createDefault();
  437. // try {
  438. // // 创建httpget.
  439. // HttpGet httpget = new HttpGet(httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
  440. // System.out.println("executing request " + httpget.getURI());
  441. // // 执行get请求.
  442. // CloseableHttpResponse response = httpclient.execute(httpget);
  443. // try {
  444. // // 获取响应实体
  445. // HttpEntity entity = response.getEntity();
  446. // System.out.println("--------------------------------------");
  447. // // 打印响应状态
  448. // System.out.println(response.getStatusLine());
  449. // if (entity != null) {
  450. // // 打印响应内容长度
  451. // System.out.println("Response content length: " + entity.getContentLength());
  452. // // 打印响应内容
  453. // System.out.println("Response content: " + EntityUtils.toString(entity));
  454. // }
  455. // System.out.println("------------------------------------");
  456. // } finally {
  457. // response.close();
  458. // }
  459. // } catch (ClientProtocolException e) {
  460. // e.printStackTrace();
  461. // } catch (ParseException e) {
  462. // e.printStackTrace();
  463. // } catch (IOException e) {
  464. // e.printStackTrace();
  465. // } finally {
  466. // // 关闭连接,释放资源
  467. // try {
  468. // httpclient.close();
  469. // } catch (IOException e) {
  470. // e.printStackTrace();
  471. // }
  472. // }
  473. }
  474. private void getRequest() throws IOException {
  475. // //1.打开浏览器
  476. // CloseableHttpClient httpClient = HttpClients.createDefault();
  477. // //2.声明get请求
  478. // HttpGet httpGet = new HttpGet(httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
  479. // //3.发送请求
  480. // CloseableHttpResponse response = httpClient.execute(httpGet);
  481. // System.out.println("StatusCode=" + response.getStatusLine().getStatusCode());
  482. // //4.判断状态码
  483. // if (response.getStatusLine().getStatusCode() == 200) {
  484. // HttpEntity entity = response.getEntity();
  485. // //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
  486. // String string = EntityUtils.toString(entity, "utf-8");
  487. // System.out.println(string);
  488. // }
  489. // //5.关闭资源
  490. // response.close();
  491. // httpClient.close();
  492. }
  493. }