java post httpclient模拟post请求 json
时间: 2023-09-09 11:11:55 浏览: 167
您也可以使用Apache HttpClient库来模拟发送POST请求,并将JSON数据作为请求体发送。以下是一个示例代码:
```java
import org.apache.http.HttpResponse;
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 java.io.BufferedReader;
import java.io.InputStreamReader;
public class PostJsonRequest {
public static void main(String[] args) {
try {
// 设置请求URL和JSON数据
String url = "http://example.com/api";
String json = "{\"name\": \"John\", \"age\": 30}";
// 创建HttpClient和HttpPost对象
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// 将JSON数据作为请求体发送
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
// 发送请求并获取响应
HttpResponse response = client.execute(post);
// 打印响应内容
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上述示例中,我们使用了Apache HttpClient库来创建HttpClient和HttpPost对象,并将JSON数据作为请求体发送。注意:在实际使用时,您需要将URL和JSON数据替换为实际的值。
阅读全文