java 发送post请求
时间: 2023-11-15 21:58:52 浏览: 91
Java发送POST请求可以使用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;
import java.io.IOException;
public class HttpPostExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com/post");
StringEntity requestEntity = new StringEntity(
"{\"name\":\"value\"}",
ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
response.close();
}
}
}
```
这个示例代码使用HTTPClient库发送POST请求,请求的URL是http://www.example.com/post,请求体是一个JSON字符串。在发送请求之前,需要创建一个CloseableHttpClient对象,然后创建一个HttpPost对象,并设置请求体。发送请求后,可以通过CloseableHttpResponse对象获取响应结果。
阅读全文