HttpClient发送JSONObject参数的请求
时间: 2023-11-21 21:05:13 浏览: 98
可以使用HttpClient库发送JSONObject参数的请求,具体步骤如下:
1. 创建HttpClient对象:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
```
2. 创建HttpPost对象:
```java
HttpPost httpPost = new HttpPost(url);
```
其中,`url`为请求的地址。
3. 设置请求头:
```java
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
```
4. 创建JSONObject对象:
```java
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
```
其中,`key1`和`key2`为参数名,`value1`和`value2`为参数值。
5. 将JSONObject对象转换为String类型:
```java
StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
```
6. 将StringEntity对象设置到HttpPost对象中:
```java
httpPost.setEntity(entity);
```
7. 发送请求并获取响应:
```java
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String result = EntityUtils.toString(responseEntity, "utf-8");
```
其中,`result`为响应的结果。最后,记得关闭HttpClient和HttpResponse对象:
```java
response.close();
httpClient.close();
```
阅读全文
相关推荐

















