HttpClient 发送Get Post 请求 携带Header

系统管理员 2022-05-13 13:12 356阅读 0赞
  1. JSONObject userObj = JSON.parseObject(HttpClientUtil.sendHttpPost(loginUrl, map));
  2. JSONObject menuObject = JSON.parseObject(HttpClientUtil.sendHttpsGetSessionId(clubManageMenu, userObj.getString("token")));
  3. public static String sendHttpsGetSessionId(String httpUrl, String sessionId) {
  4. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  5. httpGet.setHeader(new BasicHeader("Cookie", "JSESSIONID=" + sessionId));
  6. return sendHttpsGet(httpGet);
  7. }
  8. /** * 发送Get请求Https */
  9. private static String sendHttpsGet(HttpGet httpGet) {
  10. CloseableHttpClient httpClient = null;
  11. CloseableHttpResponse response = null;
  12. HttpEntity entity = null;
  13. String responseContent = null;
  14. try {
  15. // 创建默认的httpClient实例.
  16. PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
  17. DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
  18. httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
  19. httpGet.setConfig(requestConfig);
  20. // 执行请求
  21. response = httpClient.execute(httpGet);
  22. entity = response.getEntity();
  23. responseContent = EntityUtils.toString(entity, "UTF-8");
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. } finally {
  27. try {
  28. // 关闭连接,释放资源
  29. if (response != null) {
  30. response.close();
  31. }
  32. if (httpClient != null) {
  33. httpClient.close();
  34. }
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. return responseContent;
  40. }
  41. /** * 发送Post请求 * * @param httpPost * @return */
  42. private static String sendHttpPost(HttpPost httpPost) {
  43. CloseableHttpClient httpClient = null;
  44. CloseableHttpResponse response = null;
  45. HttpEntity entity = null;
  46. String responseContent = null;
  47. try {
  48. // 创建默认的httpClient实例.
  49. RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
  50. httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
  51. httpClient = HttpClients.createDefault();
  52. httpPost.setConfig(requestConfig);
  53. // 执行请求
  54. response = httpClient.execute(httpPost);
  55. entity = response.getEntity();
  56. responseContent = EntityUtils.toString(entity, "UTF-8");
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. } finally {
  60. try {
  61. // 关闭连接,释放资源
  62. if (response != null) {
  63. response.close();
  64. }
  65. if (httpClient != null) {
  66. httpClient.close();
  67. }
  68. } catch (IOException e) {
  69. e.printStackTrace();
  70. }
  71. }
  72. return responseContent;
  73. }

发表评论

表情:
评论列表 (有 0 条评论,356人围观)

还没有评论,来说两句吧...

相关阅读