Java 发送 POST 请求并传递 JSON 参数 - 使用 Apache HttpClient
在 Java 中,可以使用不同的库来发送 POST 请求并传递 JSON 参数。以下是使用常见的 Apache HttpClient 库的示例代码:
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 Main {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置 JSON 参数
String json = '{"name": "John", "age": 30}';
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
// 处理响应
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
}
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码将发送一个 POST 请求到 http://example.com/api/endpoint,并传递 JSON 参数 '{"name": "John", "age": 30}'。你可以根据实际情况修改 URL、请求头和 JSON 参数。
原文地址: https://www.cveoy.top/t/topic/pkm9 著作权归作者所有。请勿转载和采集!