Apache HttpClient

谁践踏了优雅 2023-10-11 11:12 87阅读 0赞

一、Apache HttpClient:

  HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。

二、Apache HttpClient 使用流程:

  • 创建 HttpClient 对象。
  • 创建请求方法的实例,并指定请求 URL。如果需要发送 GET 请求,创建 HttpGet 对象;如果需要发送 POST 请求,创建 HttpPost 对象。
  • 如果需要发送请求参数,可调用 HttpGetHttpPost 共同的 setParams(HttpParams params) 方法来添加请求参数;对于 HttpPost 对象而言,也可调用 setEntity(HttpEntity entity) 方法来设置请求参数。
  • 调用 HttpClient 对象的 execute(HttpUriRequest request) 发送请求,该方法返回一个 HttpResponse
  • 调用 HttpResponsegetAllHeaders()getHeaders(String name) 等方法可获取服务器的响应头;调用 HttpResponsegetEntity() 方法可获取 HttpEntity 对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  • 释放连接。无论执行方法是否成功,都必须释放连接

三、示例:

(1)依赖:

ContractedBlock.gif ExpandedBlockStart.gif

  1. <!-- Apache Http Begin -->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents</groupId>
  4. <artifactId>httpclient</artifactId>
  5. <version>4.5.5</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.httpcomponents</groupId>
  9. <artifactId>fluent-hc</artifactId>
  10. <version>4.5.5</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.apache.httpcomponents</groupId>
  14. <artifactId>httpmime</artifactId>
  15. <version>4.5.5</version>
  16. </dependency>
  17. <!-- Apache Http End -->

pom.xml

(2)测试:

  1. public class HttpClientTest {
  2. public static void main(String[] args) {
  3. get();
  4. }
  5. private static void get() {
  6. // 创建 HttpClient 客户端
  7. CloseableHttpClient httpClient = HttpClients.createDefault();
  8. // 创建 HttpGet 请求
  9. HttpGet httpGet = new HttpGet("http://www.baidu.com");
  10. // 设置长连接
  11. httpGet.setHeader("Connection", "keep-alive");
  12. // 设置代理(模拟浏览器版本)
  13. httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
  14. // 设置 Cookie
  15. httpGet.setHeader("Cookie", "UM_distinctid=16442706a09352-0376059833914f-3c604504-1fa400-16442706a0b345; CNZZDATA1262458286=1603637673-1530123020-%7C1530123020; JSESSIONID=805587506F1594AE02DC45845A7216A4");
  16. CloseableHttpResponse httpResponse = null;
  17. try {
  18. // 请求并获得响应结果
  19. httpResponse = httpClient.execute(httpGet);
  20. HttpEntity httpEntity = httpResponse.getEntity();
  21. // 输出请求结果
  22. System.out.println(EntityUtils.toString(httpEntity));
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. // 无论如何必须关闭连接
  27. finally {
  28. if (httpResponse != null) {
  29. try {
  30. httpResponse.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. if (httpClient != null) {
  36. try {
  37. httpClient.close();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. }
  44. }

四、工具类:

ContractedBlock.gif ExpandedBlockStart.gif

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.client.entity.UrlEncodedFormEntity;
  3. import org.apache.http.client.methods.CloseableHttpResponse;
  4. import org.apache.http.client.methods.HttpGet;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.message.BasicNameValuePair;
  9. import org.apache.http.util.EntityUtils;
  10. import java.io.IOException;
  11. import java.util.Arrays;
  12. /**
  13. * HttpClient工具类
  14. */
  15. public class HttpClientUtils {
  16. private static final String REQUEST_METHOD_GET = "GET";
  17. private static final String REQUEST_METHOD_POST = "POST";
  18. private static final String REQUEST_HEADER_CONNECTION = "keep-alive";
  19. private static final String REQUEST_HEADER_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
  20. /**
  21. * Get请求
  22. *
  23. * @param url 路径
  24. * @return 字符串
  25. */
  26. public static String doGet(String url) {
  27. String result = HttpClientUtils.getResult("GET", url, null);
  28. return result;
  29. }
  30. /**
  31. * GET请求
  32. *
  33. * @param url API
  34. * @param cookie cookie
  35. * @return json字符串
  36. */
  37. public static String doGet(String url, String cookie) {
  38. String result = HttpClientUtils.getResult("GET", url, cookie);
  39. return result;
  40. }
  41. /**
  42. * POST请求
  43. *
  44. * @param url
  45. * @param params 请求参数
  46. * @return json字符串
  47. */
  48. public static String doPost(String url, BasicNameValuePair... params) {
  49. String result = HttpClientUtils.getResult("POST", url, null, params);
  50. return result;
  51. }
  52. /**
  53. * POST请求
  54. *
  55. * @param url
  56. * @param cookie
  57. * @param params 请求参数
  58. * @return json字符串
  59. */
  60. public static String doPost(String url, String cookie, BasicNameValuePair... params) {
  61. String result = HttpClientUtils.getResult("POST", url, cookie, params);
  62. return result;
  63. }
  64. /**
  65. * 使用HttpClient通过API请求来获得json字符串
  66. *
  67. * @param requestMethod 请求方式
  68. * @param url 请求路径
  69. * @param cookie cookie
  70. * @param params 请求参数
  71. * @return json字符串
  72. */
  73. private static String getResult(String requestMethod, String url, String cookie, BasicNameValuePair... params) {
  74. CloseableHttpClient httpClient = HttpClients.createDefault();
  75. CloseableHttpResponse httpResponse = null;
  76. String result = null;
  77. try {
  78. //GET
  79. if (requestMethod.equals(HttpClientUtils.REQUEST_METHOD_GET)) {
  80. HttpGet httpGet = new HttpGet(url);
  81. httpGet.setHeader("Connection", HttpClientUtils.REQUEST_HEADER_CONNECTION);
  82. httpGet.setHeader("Cookie", cookie);
  83. httpGet.setHeader("User-Agent", HttpClientUtils.REQUEST_HEADER_USER_AGENT);
  84. httpResponse = httpClient.execute(httpGet);
  85. }
  86. //POST
  87. else if (requestMethod.equals(HttpClientUtils.REQUEST_METHOD_POST)) {
  88. HttpPost httpPost = new HttpPost(url);
  89. httpPost.setHeader("Connection", HttpClientUtils.REQUEST_HEADER_CONNECTION);
  90. httpPost.setHeader("Cookie", cookie);
  91. httpPost.setHeader("User-Agent", HttpClientUtils.REQUEST_HEADER_USER_AGENT);
  92. httpPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(params)));
  93. httpResponse = httpClient.execute(httpPost);
  94. }
  95. //----
  96. HttpEntity entity = httpResponse.getEntity();
  97. result = EntityUtils.toString(entity);
  98. } catch (IOException e) {
  99. e.printStackTrace();
  100. } finally {
  101. if (httpClient != null) {
  102. try {
  103. httpClient.close();
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. }
  109. return result;
  110. }
  111. }

HttpClientUtils

转载于:https://www.cnblogs.com/Tractors/p/11360890.html

发表评论

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

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

相关阅读