httpclient get请求 解析response
时间: 2023-10-10 08:04:25 浏览: 79
HttpClient 卡死 response 为 null - 帐前卒 - CSDN1
对于 HttpClient 发送 GET 请求返回的响应,我们可以通过以下步骤进行解析:
1. 获取响应状态码:
```java
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
```
2. 获取响应头信息:
```java
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
System.out.println(header.getName() + " : " + header.getValue());
}
```
3. 获取响应体信息:
```java
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
```
完整的代码示例:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status Code: " + statusCode);
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
System.out.println(header.getName() + " : " + header.getValue());
}
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
System.out.println("Response Content: " + responseContent);
```
需要注意的是,这里的 EntityUtils.toString 方法需要传入编码格式参数,根据实际情况进行选择。同时,使用完 HttpClient 后需要关闭资源:
```java
httpClient.close();
```
阅读全文