Apache HttpClient POST HTTP请求示例

x33g5p2x  于2022-10-07 转载在 Apache  
字(7.5k)|赞(0)|评价(0)|浏览(1365)

在这篇快速文章中,我们将逐步讨论如何使用Apache HttpClient 4.5来进行HTTP POST请求。HTTP POST请求方法要求服务器接受请求中所包含的实体作为URI识别的网络资源的一个新的下级。

HttpClient支持HTTP/1.1规范中定义的所有HTTP方法:GETHEADPOSTPUTDELETETRACEOPTIONS。每种方法类型都有一个特定的类:HttpGetHttpHeadHttpPostHttpPutHttpDeleteHttpTrace、和HttpOptions
在这个例子中,我们将使用HttpPost类来处理POST HTTP方法。查看Apache HttpClient GET HTTP请求实例

使用Apache HttpClient - 添加依赖性

Apache HttpClient库允许处理HTTP请求。要使用这个库,请在你的Maven或Gradle构建文件中添加一个依赖项。你可以在这里找到最新版本:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

我们使用maven来管理我们的依赖关系,并使用Apache HttpClient 4.5版本。在你的项目中添加以下依赖项,以便进行HTTP POST请求方式。

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5</version>
  5. </dependency>

开发步骤

让我们创建一个逐步的例子,用HttpClient来做一个HTTP POST请求。

1. 使用辅助类HttpClients创建CloseableHttpClient的实例。

  1. CloseableHttpClient httpclient = HttpClients.createDefault()

HttpClients.createDefault()方法以默认配置创建CloseableHttpClient实例。

2. 创建一个基本的POST请求

  1. HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");

3. 为Post HTTP请求添加头信息

  1. HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
  2. httpPost.setHeader("Accept", "application/json");
  3. httpPost.setHeader("Content-type", "application/json");

3. 在Post请求中添加JSON数据

  1. String json = "{\r\n" +
  2. " \"firstName\": \"Ram\",\r\n" +
  3. " \"lastName\": \"Jadhav\",\r\n" +
  4. " \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
  5. " \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
  6. " \"createdBy\": \"Ramesh\",\r\n" +
  7. " \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
  8. " \"updatedby\": \"Ramesh\"\r\n" +
  9. "}";
  10. StringEntity stringEntity = new StringEntity(json);
  11. httpPost.setEntity(stringEntity);

4. 创建一个自定义的响应处理程序

  1. ResponseHandler < String > responseHandler = response - > {
  2. int status = response.getStatusLine().getStatusCode();
  3. if (status >= 200 && status < 300) {
  4. HttpEntity entity = response.getEntity();
  5. return entity != null ? EntityUtils.toString(entity) : null;
  6. } else {
  7. throw new ClientProtocolException("Unexpected response status: " + status);
  8. }
  9. };

5. 通过execute()方法发送基本的POST请求

  1. String responseBody = httpclient.execute(httpPost, responseHandler);

HttpClient HTTP POST请求方法实例

让我们来讨论如何在实时项目中使用HttpClient。考虑到我们已经部署了Spring Boot Restful CRUD APIs。请看这篇文章 - Spring Boot 2 + hibernate 5 + CRUD REST API教程。

在下面的例子中,我们发送一个资源给http://localhost:8080/api/v1/users。这个资源接受请求的JSON,对其进行处理并将其存储到数据库中。这个服务还返回一个带有资源的响应。在这个例子中,我们使用Java 7 try-with-resources来自动处理ClosableHttpClient的关闭,我们也使用Java 8 lambdas来处理ResponseHandler

  1. package com.javadevelopersguide.httpclient.examples;
  2. import java.io.IOException;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.client.ClientProtocolException;
  5. import org.apache.http.client.ResponseHandler;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.util.EntityUtils;
  11. /**
  12. * This example demonstrates the use of {@link HttpPost} request method.
  13. * @author Ramesh Fadatare
  14. */
  15. public class HttpPostRequestMethodExample {
  16. public static void main(String[] args) throws IOException {
  17. postUser();
  18. }
  19. public static void postUser() throws IOException {
  20. try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
  21. HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
  22. httpPost.setHeader("Accept", "application/json");
  23. httpPost.setHeader("Content-type", "application/json");
  24. String json = "{\r\n" +
  25. " \"firstName\": \"Ram\",\r\n" +
  26. " \"lastName\": \"Jadhav\",\r\n" +
  27. " \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
  28. " \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
  29. " \"createdBy\": \"Ramesh\",\r\n" +
  30. " \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
  31. " \"updatedby\": \"Ramesh\"\r\n" +
  32. "}";
  33. StringEntity stringEntity = new StringEntity(json);
  34. httpPost.setEntity(stringEntity);
  35. System.out.println("Executing request " + httpPost.getRequestLine());
  36. // Create a custom response handler
  37. ResponseHandler < String > responseHandler = response - > {
  38. int status = response.getStatusLine().getStatusCode();
  39. if (status >= 200 && status < 300) {
  40. HttpEntity entity = response.getEntity();
  41. return entity != null ? EntityUtils.toString(entity) : null;
  42. } else {
  43. throw new ClientProtocolException("Unexpected response status: " + status);
  44. }
  45. };
  46. String responseBody = httpclient.execute(httpPost, responseHandler);
  47. System.out.println("----------------------------------------");
  48. System.out.println(responseBody);
  49. }
  50. }
  51. }

输出

  1. Executing request POST http://localhost:8080/api/v1/users HTTP/1.1
  2. ----------------------------------------
  3. {"id":37,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh1234@gmail.com",
  4. "createdAt":"2018-10-29T09:37:09.821+0000","createdBy":"Ramesh","updatedAt":"2018-10-29T09:37:09.821+0000",
  5. "updatedby":"Ramesh"}

更多的例子

在下面的例子中,我们向资源http://httpbin.org/post发布数据。该资源确认数据并返回一个JSON对象,我们将简单地打印到控制台。 

  1. package com.javadevelopersguide.httpclient.examples;
  2. import java.io.IOException;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.client.ClientProtocolException;
  5. import org.apache.http.client.ResponseHandler;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.util.EntityUtils;
  11. /**
  12. * This example demonstrates the use of {@link HttpPost} request method.
  13. */
  14. public class HttpPostRequestMethodExample {
  15. public static void main(String[] args) throws IOException {
  16. post();
  17. }
  18. public static void post() throws IOException {
  19. try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
  20. HttpPost httpPost = new HttpPost("http://httpbin.org/post");
  21. httpPost.setEntity(new StringEntity("Hello, World"));
  22. System.out.println("Executing request " + httpPost.getRequestLine());
  23. // Create a custom response handler
  24. ResponseHandler < String > responseHandler = response - > {
  25. int status = response.getStatusLine().getStatusCode();
  26. if (status >= 200 && status < 300) {
  27. HttpEntity entity = response.getEntity();
  28. return entity != null ? EntityUtils.toString(entity) : null;
  29. } else {
  30. throw new ClientProtocolException("Unexpected response status: " + status);
  31. }
  32. };
  33. String responseBody = httpclient.execute(httpPost, responseHandler);
  34. System.out.println("----------------------------------------");
  35. System.out.println(responseBody);
  36. }
  37. }
  38. }

输出

  1. Executing request POST http://httpbin.org/post HTTP/1.1
  2. ----------------------------------------
  3. {
  4. "args": {},
  5. "data": "Hello, World",
  6. "files": {},
  7. "form": {},
  8. "headers": {
  9. "Accept-Encoding": "gzip,deflate",
  10. "Connection": "close",
  11. "Content-Length": "12",
  12. "Content-Type": "text/plain; charset=ISO-8859-1",
  13. "Host": "httpbin.org",
  14. "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  15. },
  16. "json": null,
  17. "origin": "49.35.12.218",
  18. "url": "http://httpbin.org/post"
  19. }

相关文章