JAVA利用HttpClient发送http请求

「爱情、让人受尽委屈。」 2022-06-18 02:16 441阅读 0赞

HttpClient官网
这里只是给自己做个笔记,记住有这个东西,看到此文章的人建议去官网学习使用
下面是官网简单的例子:

  1. package org.apache.hc.client5.http.examples;
  2. import java.io.IOException;
  3. import org.apache.hc.client5.http.impl.sync.CloseableHttpClient;
  4. import org.apache.hc.client5.http.impl.sync.HttpClients;
  5. import org.apache.hc.client5.http.methods.HttpGet;
  6. import org.apache.hc.client5.http.protocol.ClientProtocolException;
  7. import org.apache.hc.client5.http.sync.ResponseHandler;
  8. import org.apache.hc.core5.http.HttpEntity;
  9. import org.apache.hc.core5.http.HttpResponse;
  10. import org.apache.hc.core5.http.ParseException;
  11. import org.apache.hc.core5.http.entity.EntityUtils;
  12. /** * This example demonstrates the use of the {@link ResponseHandler} to simplify * the process of processing the HTTP response and releasing associated resources. */
  13. public class ClientWithResponseHandler {
  14. public final static void main(String[] args) throws Exception {
  15. try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
  16. HttpGet httpget = new HttpGet("http://httpbin.org/get");
  17. System.out.println("Executing request " + httpget.getRequestLine());
  18. // Create a custom response handler
  19. ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
  20. @Override
  21. public String handleResponse(
  22. final HttpResponse response) throws IOException {
  23. int status = response.getStatusLine().getStatusCode();
  24. if (status >= 200 && status < 300) {
  25. HttpEntity entity = response.getEntity();
  26. try {
  27. return entity != null ? EntityUtils.toString(entity) : null;
  28. } catch (ParseException ex) {
  29. throw new ClientProtocolException(ex);
  30. }
  31. } else {
  32. throw new ClientProtocolException("Unexpected response status: " + status);
  33. }
  34. }
  35. };
  36. String responseBody = httpclient.execute(httpget, responseHandler);
  37. System.out.println("----------------------------------------");
  38. System.out.println(responseBody);
  39. }
  40. }
  41. }

MAVEN依赖:

  1. <dependency> <groupId>org.apache.httpcomponents.client5</groupId>
  2. <artifactId>httpclient5</artifactId>
  3. <version>5.0-alpha1</version>
  4. </dependency>

发表评论

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

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

相关阅读