httpclient post请求代码
时间: 2023-11-01 09:08:06 浏览: 52
以下是使用 Apache HttpClient 发送 POST 请求的 Java 代码示例:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientPOST {
public static void main(String[] args) throws IOException {
String url = "https://example.com/api/v1/users";
String requestBody = "{\"name\":\"John Doe\",\"email\":\"johndoe@example.com\"}";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
// 将请求体设置为 StringEntity
StringEntity stringEntity = new StringEntity(requestBody);
httpPost.setEntity(stringEntity);
// 执行 POST 请求
HttpEntity responseEntity = httpClient.execute(httpPost).getEntity();
// 读取响应体
String response = EntityUtils.toString(responseEntity);
System.out.println(response);
}
}
```
在上述示例中,我们使用 `HttpClientBuilder` 类创建了一个 `HttpClient` 实例,并使用 `HttpPost` 类创建了一个 POST 请求对象。然后,将请求体设置为 `StringEntity`,并将其传递给 POST 请求对象。最后,使用 `HttpClient` 实例执行 POST 请求,并读取响应体。
阅读全文