在这篇快速文章中,我们将逐步讨论如何使用Apache HttpClient 4.5
来进行HTTP POST请求。HTTP POST请求方法要求服务器接受请求中所包含的实体作为URI识别的网络资源的一个新的下级。
HttpClient
支持HTTP/1.1规范中定义的所有HTTP方法:GET
、HEAD
、POST
、PUT
、DELETE
、TRACE
和OPTIONS
。每种方法类型都有一个特定的类:HttpGet
、HttpHead
、HttpPost
、HttpPut
、HttpDelete
、HttpTrace
、和HttpOptions
。
在这个例子中,我们将使用HttpPost类来处理POST HTTP方法。查看Apache HttpClient GET HTTP请求实例
Apache HttpClient
库允许处理HTTP请求。要使用这个库,请在你的Maven或Gradle构建文件中添加一个依赖项。你可以在这里找到最新版本:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
我们使用maven来管理我们的依赖关系,并使用Apache HttpClient 4.5版本。在你的项目中添加以下依赖项,以便进行HTTP POST请求方式。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
让我们创建一个逐步的例子,用HttpClient
来做一个HTTP POST请求。
CloseableHttpClient httpclient = HttpClients.createDefault()
HttpClients.createDefault()
方法以默认配置创建CloseableHttpClient
实例。
HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
String json = "{\r\n" +
" \"firstName\": \"Ram\",\r\n" +
" \"lastName\": \"Jadhav\",\r\n" +
" \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
" \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
" \"createdBy\": \"Ramesh\",\r\n" +
" \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
" \"updatedby\": \"Ramesh\"\r\n" +
"}";
StringEntity stringEntity = new StringEntity(json);
httpPost.setEntity(stringEntity);
ResponseHandler < String > responseHandler = response - > {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
让我们来讨论如何在实时项目中使用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
。
package com.javadevelopersguide.httpclient.examples;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates the use of {@link HttpPost} request method.
* @author Ramesh Fadatare
*/
public class HttpPostRequestMethodExample {
public static void main(String[] args) throws IOException {
postUser();
}
public static void postUser() throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
String json = "{\r\n" +
" \"firstName\": \"Ram\",\r\n" +
" \"lastName\": \"Jadhav\",\r\n" +
" \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
" \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
" \"createdBy\": \"Ramesh\",\r\n" +
" \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
" \"updatedby\": \"Ramesh\"\r\n" +
"}";
StringEntity stringEntity = new StringEntity(json);
httpPost.setEntity(stringEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response - > {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}
}
Executing request POST http://localhost:8080/api/v1/users HTTP/1.1
----------------------------------------
{"id":37,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh1234@gmail.com",
"createdAt":"2018-10-29T09:37:09.821+0000","createdBy":"Ramesh","updatedAt":"2018-10-29T09:37:09.821+0000",
"updatedby":"Ramesh"}
在下面的例子中,我们向资源http://httpbin.org/post发布数据。该资源确认数据并返回一个JSON对象,我们将简单地打印到控制台。
package com.javadevelopersguide.httpclient.examples;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates the use of {@link HttpPost} request method.
*/
public class HttpPostRequestMethodExample {
public static void main(String[] args) throws IOException {
post();
}
public static void post() throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
httpPost.setEntity(new StringEntity("Hello, World"));
System.out.println("Executing request " + httpPost.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response - > {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}
}
Executing request POST http://httpbin.org/post HTTP/1.1
----------------------------------------
{
"args": {},
"data": "Hello, World",
"files": {},
"form": {},
"headers": {
"Accept-Encoding": "gzip,deflate",
"Connection": "close",
"Content-Length": "12",
"Content-Type": "text/plain; charset=ISO-8859-1",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
},
"json": null,
"origin": "49.35.12.218",
"url": "http://httpbin.org/post"
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/apache-httpclient-post-http-request-example.html
内容来源于网络,如有侵权,请联系作者删除!