Java HttpClient 发送 POST 请求示例代码
以下是 Java 中使用 HttpClient 库发送一个 POST 请求的示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
import java.io.IOException;
public class PostRequestExample {
public static void main(String[] args) {
String url = 'https://example.com/api/post';
String requestBody = '{"name":"John", "age":30}';
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity requestEntity = new StringEntity(requestBody, 'UTF-8');
httpPost.setEntity(requestEntity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, 'UTF-8');
System.out.println(responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个示例中,我们首先定义了要请求的 URL 和请求体。然后创建一个 CloseableHttpClient 对象,这个对象负责发送 HTTP 请求和接收 HTTP 响应。接着,我们创建一个 HttpPost 对象,并将请求体设置到请求中。最后,我们使用 httpClient 对象的 execute 方法发送 POST 请求,并使用 response 对象获取响应实体并解析响应内容。最后,我们关闭 httpClient 和 response。
原文地址: https://www.cveoy.top/t/topic/mqOt 著作权归作者所有。请勿转载和采集!