Java如何使用HttpClient发送带有JSON正文的POST请求?
下面的代码片段展示了如何使用HttpClient发送带有JSON主体的POST请求。本例中的有效负载是包含id、first_name和last_name的用户信息。我们将有效负载放置在一个名为StringEntity的对象中,并将其内容类型设置为ContentType.APPLICATION_FORM_URLENCODED。
在这个post请求调用的另一端,可以使用HttpServletRequest.getParameter()方法在Java
Servlet中读取数据。例如,要读取下面发送的JSON正文,我们可以调用request.getParameter("data")。这将给我们使用HttpClient
Post请求发送的有效负载。
让我们跳入下面的代码片段:
package org.nhooo.example.httpclient;import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpPostJsonExample {
public static void main(String[] args) throws Exception {
String payload = "data={" +
"\"username\": \"admin\", " +
"\"first_name\": \"System\", " +
"\"last_name\": \"Administrator\"" +
"}";
StringEntity entity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8080/register");
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
}
}
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.9/httpclient-4.5.9.jar --><groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
以上是 Java如何使用HttpClient发送带有JSON正文的POST请求? 的全部内容, 来源链接: utcz.com/z/343186.html