HttpUtils.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package com.yihu.jw.care.util.http;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpStatus;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.auth.AuthScope;
  6. import org.apache.http.auth.UsernamePasswordCredentials;
  7. import org.apache.http.client.CredentialsProvider;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.*;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.BasicCredentialsProvider;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.util.EntityUtils;
  16. import org.springframework.util.StringUtils;
  17. import java.io.BufferedReader;
  18. import java.io.InputStream;
  19. import java.io.InputStreamReader;
  20. import java.net.URL;
  21. import java.net.URLConnection;
  22. import java.util.ArrayList;
  23. import java.util.List;
  24. import java.util.Map;
  25. /**
  26. * Utils - HTTP请求辅助工具类
  27. * Created by progr1mmer on 2017/9/27.
  28. */
  29. public class HttpUtils {
  30. public static HttpResponse doGet(String url, Map<String, Object> params) throws Exception {
  31. return doGet(url, params, null);
  32. }
  33. public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
  34. return doGet(url, params, headers, null, null);
  35. }
  36. public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
  37. String response;
  38. int status;
  39. CloseableHttpClient httpClient = null;
  40. CloseableHttpResponse closeableHttpResponse = null;
  41. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  42. if (params != null) {
  43. for (String key : params.keySet()) {
  44. Object value = params.get(key);
  45. if (value != null) {
  46. nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
  47. }
  48. }
  49. }
  50. String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
  51. HttpGet httpGet = new HttpGet(url + "?" + paramStr);
  52. if (headers != null) {
  53. for (String key : headers.keySet()) {
  54. httpGet.addHeader(key, headers.get(key));
  55. }
  56. }
  57. try {
  58. if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  59. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
  60. CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  61. credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
  62. httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
  63. } else {
  64. httpClient = HttpClients.createDefault();
  65. }
  66. closeableHttpResponse = httpClient.execute(httpGet);
  67. HttpEntity resEntity = closeableHttpResponse.getEntity();
  68. status = closeableHttpResponse.getStatusLine().getStatusCode();
  69. response = getRespString(resEntity);
  70. } finally {
  71. try {
  72. if (closeableHttpResponse != null) {
  73. closeableHttpResponse.close();
  74. }
  75. if (httpClient != null) {
  76. httpClient.close();
  77. }
  78. }catch (Exception e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. if (status != HttpStatus.SC_OK) {
  83. // LogService.getLogger().error(" GET: " + url + " " + status);
  84. }
  85. HttpResponse httpResponse = new HttpResponse(status, response);
  86. return httpResponse;
  87. }
  88. public static HttpResponse doPost(String url, Map<String, Object> params) throws Exception {
  89. return doPost(url, params, null);
  90. }
  91. public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers) throws Exception{
  92. return doPost(url, params, headers, null, null);
  93. }
  94. public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception{
  95. String response;
  96. int status;
  97. CloseableHttpClient httpClient = null;
  98. CloseableHttpResponse closeableHttpResponse = null;
  99. HttpPost httpPost = new HttpPost(url);
  100. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  101. if (params != null) {
  102. for (String key : params.keySet()) {
  103. Object value = params.get(key);
  104. if (value != null) {
  105. nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
  106. }
  107. }
  108. }
  109. httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
  110. if (headers != null) {
  111. for (String key : headers.keySet()) {
  112. httpPost.addHeader(key, headers.get(key));
  113. }
  114. }
  115. try {
  116. if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  117. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
  118. CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  119. credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
  120. httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
  121. } else {
  122. httpClient = HttpClients.createDefault();
  123. }
  124. closeableHttpResponse = httpClient.execute(httpPost);
  125. HttpEntity resEntity = closeableHttpResponse.getEntity();
  126. status = closeableHttpResponse.getStatusLine().getStatusCode();
  127. response = getRespString(resEntity);
  128. } finally {
  129. try {
  130. if (closeableHttpResponse != null) {
  131. closeableHttpResponse.close();
  132. }
  133. if (httpClient != null) {
  134. httpClient.close();
  135. }
  136. }catch (Exception e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. if(status != HttpStatus.SC_OK) {
  141. // LogService.getLogger().error(" POST: " + url + " " + status);
  142. }
  143. HttpResponse httpResponse = new HttpResponse(status, response);
  144. return httpResponse;
  145. }
  146. public static HttpResponse doJsonPost(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception{
  147. String response;
  148. int status;
  149. CloseableHttpClient httpClient = null;
  150. CloseableHttpResponse closeableHttpResponse = null;
  151. HttpPost httpPost = new HttpPost(url);
  152. httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
  153. httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
  154. if (headers != null) {
  155. for (String key : headers.keySet()) {
  156. httpPost.addHeader(key, headers.get(key));
  157. }
  158. }
  159. try {
  160. if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  161. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
  162. CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  163. credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
  164. httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
  165. } else {
  166. httpClient = HttpClients.createDefault();
  167. }
  168. closeableHttpResponse = httpClient.execute(httpPost);
  169. HttpEntity resEntity = closeableHttpResponse.getEntity();
  170. status = closeableHttpResponse.getStatusLine().getStatusCode();
  171. response = getRespString(resEntity);
  172. } finally {
  173. try {
  174. if (closeableHttpResponse != null) {
  175. closeableHttpResponse.close();
  176. }
  177. if (httpClient != null) {
  178. httpClient.close();
  179. }
  180. } catch (Exception e) {
  181. e.printStackTrace();
  182. }
  183. }
  184. if(status != HttpStatus.SC_OK) {
  185. // LogService.getLogger().error(" POST: " + url + " " + status);
  186. }
  187. HttpResponse httpResponse = new HttpResponse(status, response);
  188. return httpResponse;
  189. }
  190. public static HttpResponse doPut(String url, Map<String, Object> params) throws Exception {
  191. return doPut(url, params, null);
  192. }
  193. public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
  194. return doPut(url, params, headers, null, null);
  195. }
  196. public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
  197. String response;
  198. int status;
  199. CloseableHttpClient httpClient = null;
  200. CloseableHttpResponse closeableHttpResponse = null;
  201. HttpPut httpPut = new HttpPut(url);
  202. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  203. if (params != null) {
  204. for (String key : params.keySet()) {
  205. Object value = params.get(key);
  206. if (value != null) {
  207. nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
  208. }
  209. }
  210. }
  211. httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
  212. if (headers != null) {
  213. for (String key : headers.keySet()) {
  214. httpPut.addHeader(key, headers.get(key));
  215. }
  216. }
  217. try {
  218. if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  219. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
  220. CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  221. credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
  222. httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
  223. } else {
  224. httpClient = HttpClients.createDefault();
  225. }
  226. closeableHttpResponse = httpClient.execute(httpPut);
  227. HttpEntity resEntity = closeableHttpResponse.getEntity();
  228. status = closeableHttpResponse.getStatusLine().getStatusCode();
  229. response = getRespString(resEntity);
  230. } finally {
  231. try {
  232. if (closeableHttpResponse != null) {
  233. closeableHttpResponse.close();
  234. }
  235. if (httpClient != null) {
  236. httpClient.close();
  237. }
  238. } catch (Exception e) {
  239. e.printStackTrace();
  240. }
  241. }
  242. if (status != HttpStatus.SC_OK) {
  243. // LogService.getLogger().error(" PUT: " + url + " " + status);
  244. }
  245. HttpResponse httpResponse = new HttpResponse(status, response);
  246. return httpResponse;
  247. }
  248. public static HttpResponse doJsonPut(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception {
  249. String response;
  250. int status;
  251. CloseableHttpClient httpClient = null;
  252. CloseableHttpResponse closeableHttpResponse = null;
  253. HttpPut httpPut = new HttpPut(url);
  254. httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
  255. httpPut.setEntity(new StringEntity(jsonData, "UTF-8"));
  256. if (headers != null) {
  257. for (String key : headers.keySet()) {
  258. httpPut.addHeader(key, headers.get(key));
  259. }
  260. }
  261. try {
  262. if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  263. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
  264. CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  265. credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
  266. httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
  267. } else {
  268. httpClient = HttpClients.createDefault();
  269. }
  270. closeableHttpResponse = httpClient.execute(httpPut);
  271. HttpEntity resEntity = closeableHttpResponse.getEntity();
  272. status = closeableHttpResponse.getStatusLine().getStatusCode();
  273. response = getRespString(resEntity);
  274. } finally {
  275. try {
  276. if (closeableHttpResponse != null) {
  277. closeableHttpResponse.close();
  278. }
  279. if (httpClient != null) {
  280. httpClient.close();
  281. }
  282. } catch (Exception e) {
  283. e.printStackTrace();
  284. }
  285. }
  286. if (status != HttpStatus.SC_OK) {
  287. // LogService.getLogger().error(" PUT: " + url + " " + status);
  288. }
  289. HttpResponse httpResponse = new HttpResponse(status, response);
  290. return httpResponse;
  291. }
  292. public static HttpResponse doDelete(String url, Map<String, Object> params) throws Exception {
  293. return doDelete(url, params, null);
  294. }
  295. public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
  296. return doDelete(url, params, headers, null, null);
  297. }
  298. public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
  299. String response;
  300. int status;
  301. CloseableHttpClient httpClient = null;
  302. CloseableHttpResponse closeableHttpResponse = null;
  303. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  304. if (params != null) {
  305. for (String key : params.keySet()) {
  306. Object value = params.get(key);
  307. if (value != null) {
  308. nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
  309. }
  310. }
  311. }
  312. String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
  313. HttpDelete httpDelete = new HttpDelete(url + "?" + paramStr);
  314. if (headers != null) {
  315. for (String key : headers.keySet()) {
  316. httpDelete.addHeader(key, headers.get(key));
  317. }
  318. }
  319. try {
  320. if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  321. UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
  322. CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  323. credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
  324. httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
  325. } else {
  326. httpClient = HttpClients.createDefault();
  327. }
  328. closeableHttpResponse = httpClient.execute(httpDelete);
  329. HttpEntity resEntity = closeableHttpResponse.getEntity();
  330. status = closeableHttpResponse.getStatusLine().getStatusCode();
  331. response = getRespString(resEntity);
  332. } finally {
  333. try {
  334. if (closeableHttpResponse != null) {
  335. closeableHttpResponse.close();
  336. }
  337. if (httpClient != null) {
  338. httpClient.close();
  339. }
  340. }catch (Exception e) {
  341. e.printStackTrace();
  342. }
  343. }
  344. if (status != HttpStatus.SC_OK) {
  345. // LogService.getLogger().error(" DELETE: " + url + " " + status);
  346. }
  347. HttpResponse httpResponse = new HttpResponse(status, response);
  348. return httpResponse;
  349. }
  350. private static String getRespString(HttpEntity entity) throws Exception {
  351. if (entity == null) {
  352. return null;
  353. }
  354. InputStream is = entity.getContent();
  355. BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  356. StringBuilder stringBuilder = new StringBuilder();
  357. String line;
  358. while ((line = reader.readLine()) != null) {
  359. stringBuilder.append(line);
  360. }
  361. return stringBuilder.toString();
  362. }
  363. /**
  364. * 向指定URL发送GET方法的请求
  365. *
  366. * @param url
  367. * 发送请求的URL
  368. * @param param
  369. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  370. * @return URL 所代表远程资源的响应结果
  371. */
  372. public String sendLoginGet(String url, String param,String userAgent) {
  373. String result = "";
  374. BufferedReader in = null;
  375. try {
  376. String urlNameString = url + "?" + param;
  377. URL realUrl = new URL(urlNameString);
  378. // 打开和URL之间的连接
  379. URLConnection connection = realUrl.openConnection();
  380. // 设置通用的请求属性
  381. connection.setRequestProperty("accept", "*/*");
  382. connection.setRequestProperty("connection", "Keep-Alive");
  383. connection.setRequestProperty("user-agent", userAgent);
  384. // 建立实际的连接
  385. connection.connect();
  386. // 定义 BufferedReader输入流来读取URL的响应
  387. in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  388. String line;
  389. while ((line = in.readLine()) != null) {
  390. result += line;
  391. }
  392. } catch (Exception e) {
  393. e.printStackTrace();
  394. } finally {
  395. try {
  396. if (in != null) {
  397. in.close();
  398. }
  399. } catch (Exception e2) {
  400. e2.printStackTrace();
  401. }
  402. }
  403. return result;
  404. }
  405. }