Java如何获取HTTP响应正文作为字符串?
本示例说明使用ApacheHttpComponents库时如何获取HTTP响应主体作为字符串。若要将响应主体作为字符串获取,我们可以使用EntityUtils.toString()方法。此方法读取HttpEntity对象内容的内容,并将其作为字符串返回。将使用来自实体对象的字符集转换内容。
让我们看看下面的代码片段:
package org.nhooo.example.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class EntityAsString {
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://kodejava.org");
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
//读取实体的内容,并将其作为String返回。
String content = EntityUtils.toString(entity);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.9/httpclient-4.5.9.jar -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短