本示例说明使用Apache HttpComponents库时如何获取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>