HttpClient4.4 模仿登陆及维持同一session 请求

  1. public class HttpClient {
  2. private static final Logger LOG = LogManager.getLogger(HttpClient.class);
  3. public static CloseableHttpClient httpClient = null;
  4. public static HttpClientContext context = null;
  5. public static CookieStore cookieStore = null;
  6. public static RequestConfig requestConfig = null;
  7. static {
  8. init();
  9. }
  10. private static void init() {
  11. context = HttpClientContext.create();
  12. cookieStore = new BasicCookieStore();
  13. // 配置超时时间(连接服务端超时1秒,请求数据返回超时2秒)
  14. requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
  15. .setConnectionRequestTimeout(60000).build();
  16. // 设置默认跳转以及存储cookie
  17. httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
  18. .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)
  19. .setDefaultCookieStore(cookieStore).build();
  20. }
  21. /**
  22. * http get
  23. *
  24. * @param url
  25. * @return response
  26. * @throws ClientProtocolException
  27. * @throws IOException
  28. */
  29. public static CloseableHttpResponse get(String url) throws ClientProtocolException, IOException {
  30. HttpGet httpget = new HttpGet(url);
  31. CloseableHttpResponse response = httpClient.execute(httpget, context);
  32. try {
  33. cookieStore = context.getCookieStore();
  34. List<Cookie> cookies = cookieStore.getCookies();
  35. for (Cookie cookie : cookies) {
  36. LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue());
  37. }
  38. } finally {
  39. response.close();
  40. }
  41. return response;
  42. }
  43. /**
  44. * http post
  45. *
  46. * @param url
  47. * @param parameters
  48. * form表单
  49. * @return response
  50. * @throws ClientProtocolException
  51. * @throws IOException
  52. */
  53. public static CloseableHttpResponse post(String url, String parameters)
  54. throws ClientProtocolException, IOException {
  55. HttpPost httpPost = new HttpPost(url);
  56. List<NameValuePair> nvps = toNameValuePairList(parameters);
  57. httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  58. CloseableHttpResponse response = httpClient.execute(httpPost, context);
  59. try {
  60. cookieStore = context.getCookieStore();
  61. List<Cookie> cookies = cookieStore.getCookies();
  62. for (Cookie cookie : cookies) {
  63. LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue());
  64. }
  65. } finally {
  66. response.close();
  67. }
  68. return response;
  69. }
  70. @SuppressWarnings("unused")
  71. private static List<NameValuePair> toNameValuePairList(String parameters) {
  72. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  73. String[] paramList = parameters.split("&");
  74. for (String parm : paramList) {
  75. int index = -1;
  76. for (int i = 0; i < parm.length(); i++) {
  77. index = parm.indexOf("=");
  78. break;
  79. }
  80. String key = parm.substring(0, index);
  81. String value = parm.substring(++index, parm.length());
  82. nvps.add(new BasicNameValuePair(key, value));
  83. }
  84. System.out.println(nvps.toString());
  85. return nvps;
  86. }
  87. /**
  88. * 手动增加cookie
  89. * @param name
  90. * @param value
  91. * @param domain
  92. * @param path
  93. */
  94. public void addCookie(String name, String value, String domain, String path) {
  95. BasicClientCookie cookie = new BasicClientCookie(name, value);
  96. cookie.setDomain(domain);
  97. cookie.setPath(path);
  98. cookieStore.addCookie(cookie);
  99. }
  100. /**
  101. * 把结果console出来
  102. *
  103. * @param httpResponse
  104. * @throws ParseException
  105. * @throws IOException
  106. */
  107. public static void printResponse(HttpResponse httpResponse) throws ParseException, IOException {
  108. // 获取响应消息实体
  109. HttpEntity entity = httpResponse.getEntity();
  110. // 响应状态
  111. System.out.println("status:" + httpResponse.getStatusLine());
  112. System.out.println("headers:");
  113. HeaderIterator iterator = httpResponse.headerIterator();
  114. while (iterator.hasNext()) {
  115. System.out.println("\t" + iterator.next());
  116. }
  117. // 判断响应实体是否为空
  118. if (entity != null) {
  119. // String responseString = EntityUtils.toString(entity);
  120. // System.out.println("response length:" + responseString.length());
  121. // System.out.println("response content:" + responseString.replace("\r\n", ""));
  122. }
  123. System.out.println(
  124. "------------------------------------------------------------------------------------------\r\n");
  125. }
  126. /**
  127. * 把当前cookie从控制台输出出来
  128. *
  129. */
  130. public static void printCookies() {
  131. System.out.println("headers:");
  132. cookieStore = context.getCookieStore();
  133. List<Cookie> cookies = cookieStore.getCookies();
  134. for (Cookie cookie : cookies) {
  135. System.out.println("key:" + cookie.getName() + " value:" + cookie.getValue());
  136. }
  137. }
  138. /**
  139. * 检查cookie的键值是否包含传参
  140. *
  141. * @param key
  142. * @return
  143. */
  144. public static boolean checkCookie(String key) {
  145. cookieStore = context.getCookieStore();
  146. List<Cookie> cookies = cookieStore.getCookies();
  147. boolean res = false;
  148. for (Cookie cookie : cookies) {
  149. if (cookie.getName().equals(key)) {
  150. res = true;
  151. break;
  152. }
  153. }
  154. return res;
  155. }
  156. /**
  157. * 直接把Response内的Entity内容转换成String
  158. *
  159. * @param httpResponse
  160. * @return
  161. * @throws ParseException
  162. * @throws IOException
  163. */
  164. public static String toString(CloseableHttpResponse httpResponse) throws ParseException, IOException {
  165. // 获取响应消息实体
  166. HttpEntity entity = httpResponse.getEntity();
  167. if (entity != null)
  168. return EntityUtils.toString(entity);
  169. else
  170. return null;
  171. }
  172. }