java httpclient发送post请求
时间: 2023-09-12 18:09:58 浏览: 89
以下是使用Apache HttpClient发送POST请求的示例代码:
```java
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 HttpClientExample {
public static void main(String[] args) {
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost请求实例
HttpPost httpPost = new HttpPost("http://example.com/api");
// 设置请求头信息
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体信息
String requestBody = "{\"name\": \"John\", \"age\": 30}";
StringEntity requestEntity = new StringEntity(requestBody, "UTF-8");
httpPost.setEntity(requestEntity);
// 发送POST请求并获取响应
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
// 获取响应实体
HttpEntity responseEntity = response.getEntity();
// 打印响应状态码
System.out.println(response.getStatusLine().getStatusCode());
// 打印响应内容
System.out.println(EntityUtils.toString(responseEntity));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
注意:在使用HttpClient发送POST请求时,需要设置请求头信息和请求体信息。请求头信息可以根据实际情况设置,请求体信息一般为JSON格式的字符串。需要注意的是,请求体字符串需要使用StringEntity类进行包装。在发送POST请求后,需要关闭响应和HttpClient实例。
阅读全文