HttpUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package com.alvin.common.util;
  2. import com.google.gson.Gson;
  3. import lombok.Data;
  4. import lombok.experimental.Accessors;
  5. import org.apache.http.*;
  6. import org.apache.http.client.config.RequestConfig;
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.client.methods.HttpUriRequest;
  11. import org.apache.http.client.utils.URIBuilder;
  12. import org.apache.http.cookie.Cookie;
  13. import org.apache.http.entity.StringEntity;
  14. import org.apache.http.impl.client.BasicCookieStore;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.impl.cookie.BasicClientCookie;
  18. import org.apache.http.message.BasicNameValuePair;
  19. import org.apache.http.util.EntityUtils;
  20. import java.io.BufferedOutputStream;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.net.URI;
  24. import java.net.URISyntaxException;
  25. import java.util.ArrayList;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. /**
  30. * 我的utils封装
  31. * 读取设置:url、cookies、params
  32. * 读取:response
  33. * 设置 proxy、header、超时时间
  34. *
  35. * @author Mark
  36. */
  37. @Data
  38. @Accessors(chain = true)
  39. public class HttpUtil {
  40. /** 代理 */
  41. private HttpHost proxy;
  42. /** 超时时间 5秒 */
  43. private Integer connectTimeout = 5000;
  44. /** header */
  45. private HashMap<String, String> headerMap;
  46. /** urlStr */
  47. private String urlStr;
  48. private BasicCookieStore cookieStore = new BasicCookieStore();
  49. private RequestConfig config;
  50. private HttpResponse httpResponse;
  51. /**
  52. * params参数
  53. */
  54. private List<NameValuePair> nameValuePairs = new ArrayList<>();
  55. public HttpUtil(String urlStr) {
  56. // 5秒
  57. this.urlStr = urlStr;
  58. }
  59. /**
  60. * 给url设置参数
  61. *
  62. * @param paramsMap
  63. * @throws URISyntaxException
  64. */
  65. public HttpUtil setParams(HashMap<String, String> paramsMap){
  66. for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
  67. nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  68. }
  69. return this;
  70. }
  71. /**
  72. * 获取get请求结果
  73. *
  74. * @return
  75. * @throws IOException
  76. */
  77. public String get() throws Exception {
  78. return getExecuteResult(getHttpGet());
  79. }
  80. /**
  81. * 获取post请求结果
  82. *
  83. * @param dataMap
  84. * @return
  85. * @throws IOException
  86. */
  87. public String post(HashMap<String, String> dataMap) throws Exception {
  88. HttpPost httpPost = getHttpPost();
  89. //解决中文乱码
  90. httpPost.setHeader("Content-Type", "text/html; charset=UTF-8");
  91. // 添加data
  92. if (dataMap != null) {
  93. List<NameValuePair> nameValuePairs = new ArrayList<>();
  94. for (Map.Entry<String, String> entry : dataMap.entrySet()) {
  95. nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  96. }
  97. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "utf-8");
  98. httpPost.setEntity(urlEncodedFormEntity);
  99. }
  100. return getExecuteResult(httpPost);
  101. }
  102. /**
  103. * 发送json请求
  104. * @param object
  105. * @return
  106. * @throws Exception
  107. */
  108. public String postJson(Object object) throws Exception {
  109. HttpPost httpPost = getHttpPost();
  110. //解决中文乱码
  111. httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
  112. if (object != null) {
  113. StringEntity entity = new StringEntity(new Gson().toJson(object), "utf-8");
  114. httpPost.setEntity(entity);
  115. }
  116. return getExecuteResult(httpPost);
  117. }
  118. /**
  119. * 处理get和post请求,返回html
  120. *
  121. * @param httpUriRequest
  122. * @return
  123. * @throws IOException
  124. */
  125. private String getExecuteResult(HttpUriRequest httpUriRequest) throws IOException {
  126. String returnStr;
  127. //获取一个链接
  128. CloseableHttpClient httpClient = HttpClients.custom()
  129. //.setConnectionManager(connectionManager)
  130. .setDefaultCookieStore(cookieStore).build();
  131. //设置header
  132. httpUriRequest.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
  133. if (headerMap != null) {
  134. for (Map.Entry<String, String> entry : headerMap.entrySet()) {
  135. httpUriRequest.setHeader(entry.getKey(), entry.getValue());
  136. }
  137. }
  138. httpResponse = httpClient.execute(httpUriRequest);
  139. //获取返回结果中的实体
  140. HttpEntity entity = httpResponse.getEntity();
  141. //判断是否失败
  142. if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
  143. returnStr = null;
  144. } else {
  145. //查看页面内容结果
  146. String rawHTMLContent = EntityUtils.toString(entity, "utf-8");
  147. returnStr = decodeUnicode(rawHTMLContent);
  148. }
  149. //关闭HttpEntity流
  150. EntityUtils.consume(entity);
  151. return returnStr;
  152. }
  153. /**
  154. * 设置cookies
  155. *
  156. * @param cookieMap
  157. */
  158. public void setCookies(HashMap<String, String> cookieMap) {
  159. for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
  160. BasicClientCookie clientCookie = new BasicClientCookie(entry.getKey(), entry.getValue());
  161. cookieStore.addCookie(clientCookie);
  162. }
  163. }
  164. /**
  165. * 获取cookies
  166. *
  167. * @return
  168. */
  169. public List<Cookie> getCookies() {
  170. return cookieStore.getCookies();
  171. }
  172. private HttpGet getHttpGet() throws Exception {
  173. URIBuilder uriBuilder = new URIBuilder(urlStr);
  174. if (nameValuePairs.size() > 0) {
  175. uriBuilder.addParameters(nameValuePairs);
  176. }
  177. URI uri = uriBuilder.build();
  178. HttpGet httpGet = new HttpGet(uri);
  179. httpGet.setConfig(getConfig());
  180. return httpGet;
  181. }
  182. private HttpPost getHttpPost() throws Exception {
  183. URIBuilder uriBuilder = new URIBuilder(urlStr);
  184. if (nameValuePairs.size() > 0) {
  185. uriBuilder.addParameters(nameValuePairs);
  186. }
  187. URI uri = uriBuilder.build();
  188. HttpPost httpPost = new HttpPost(uri);
  189. httpPost.setConfig(getConfig());
  190. return httpPost;
  191. }
  192. public boolean getDownLoad(String filePath) throws Exception {
  193. return downLoadFile(getHttpGet(), filePath);
  194. }
  195. public boolean PostDownLoad(String filePath) throws Exception {
  196. return downLoadFile(getHttpPost(), filePath);
  197. }
  198. /**
  199. * 下载文件到指定路径
  200. *
  201. * @param httpUriRequest
  202. * @param filePath
  203. * @return
  204. */
  205. private boolean downLoadFile(HttpUriRequest httpUriRequest, String filePath) throws IOException {
  206. CloseableHttpClient httpClient = HttpClients.custom()
  207. //.setConnectionManager(connectionManager)
  208. .setDefaultCookieStore(cookieStore).build();
  209. HttpResponse httpResponse = httpClient.execute(httpUriRequest);
  210. //判断是否失败
  211. if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
  212. return false;
  213. }
  214. //获取返回结果中的实体
  215. HttpEntity entity = httpResponse.getEntity();
  216. //存储
  217. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
  218. entity.writeTo(bos);
  219. bos.close();
  220. //关闭HttpEntity流
  221. EntityUtils.consume(entity);
  222. return true;
  223. }
  224. /**
  225. * 设置代理服务器
  226. *
  227. * @param ip
  228. * @param port
  229. * @param httpType
  230. */
  231. public HttpUtil setProxy(String ip, int port, String httpType) {
  232. this.proxy = new HttpHost(ip, port, httpType);
  233. return this;
  234. }
  235. private RequestConfig getConfig() {
  236. RequestConfig.Builder custom = RequestConfig.custom();
  237. if (proxy != null) {
  238. custom.setProxy(proxy);
  239. }
  240. /**
  241. * 设置超时时间
  242. */
  243. custom.setConnectTimeout(connectTimeout)
  244. .setSocketTimeout(connectTimeout)
  245. .setConnectionRequestTimeout(connectTimeout);
  246. return custom.build();
  247. }
  248. /**
  249. * 解析string里面的字符串,因为只有部分需要解析,所有需要判断
  250. *
  251. * @param s 字符串
  252. * @return
  253. */
  254. public String decodeUnicode(String s) {
  255. char aChar;
  256. int len = s.length();
  257. StringBuffer outBuffer = new StringBuffer(len);
  258. for (int x = 0; x < len; ) {
  259. aChar = s.charAt(x++);
  260. if (aChar == '\\') {
  261. aChar = s.charAt(x++);
  262. if (aChar == 'u') {
  263. // Read the xxxx
  264. int value = 0;
  265. for (int i = 0; i < 4; i++) {
  266. aChar = s.charAt(x++);
  267. switch (aChar) {
  268. case '0':
  269. case '1':
  270. case '2':
  271. case '3':
  272. case '4':
  273. case '5':
  274. case '6':
  275. case '7':
  276. case '8':
  277. case '9':
  278. value = (value << 4) + aChar - '0';
  279. break;
  280. case 'a':
  281. case 'b':
  282. case 'c':
  283. case 'd':
  284. case 'e':
  285. case 'f':
  286. value = (value << 4) + 10 + aChar - 'a';
  287. break;
  288. case 'A':
  289. case 'B':
  290. case 'C':
  291. case 'D':
  292. case 'E':
  293. case 'F':
  294. value = (value << 4) + 10 + aChar - 'A';
  295. break;
  296. default:
  297. throw new IllegalArgumentException(
  298. "Malformed \\uxxxx encoding.");
  299. }
  300. }
  301. outBuffer.append((char) value);
  302. } else {
  303. switch (aChar) {
  304. case 't':
  305. aChar = '\t';
  306. break;
  307. case 'r':
  308. aChar = '\r';
  309. break;
  310. case 'n':
  311. aChar = '\n';
  312. break;
  313. case 'f':
  314. aChar = '\f';
  315. break;
  316. default:
  317. break;
  318. }
  319. outBuffer.append(aChar);
  320. }
  321. } else {
  322. outBuffer.append(aChar);
  323. }
  324. }
  325. return outBuffer.toString();
  326. }
  327. public static void main(String[] args) throws Exception {
  328. String s = new HttpUtil("https://www.baidu.com").get();
  329. System.out.println(s);
  330. }
  331. }