以下是Java HttpClient发送POST请求并附带JSON Body的示例代码:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientPostJsonExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 创建POST请求
HttpPost httpPost = new HttpPost("http://example.com/api/test");
// 添加请求头信息
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json");
// 设置JSON Body
String jsonBody = "{\"key\":\"value\"}";
StringEntity entity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 解析响应结果
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
} finally {
// 关闭响应
response.close();
} finally {
// 关闭httpClient
httpClient.close();
该示例中,我们首先创建一个HttpClient实例,然后创建一个HttpPost实例,设置请求头信息以及JSON Body,并发送请求。最后获取响应并解析响应结果。