returns EntityUtils.toString(响应)到底是什么?

What exactly returns EntityUtils.toString(response)?

我正在做我的 API REST,我看到在很多例子中人们使用 EntityUtils.toString(response) 将他们的 response 从他们的 GETPOSTPUTDELETE 方法。类似这样:

HttpGet method = new HttpGet(url);
method.setHeader("content-type", "application/json");
HttpResponse response = httpClient.execute(method);
String responseString = EntityUtils.toString(response.getEntity());

请避免对我说它给了我一个字符串的答案

我知道它 returns 对我来说 String 带有实体的内容(在本例中为响应),但这是我的疑虑所在,因为我不确定这是什么 String returns。我在官方文档里看到了

Read the contents of an entity and return it as a String.

https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/util/EntityUtils.html#toString(org.apache.http.HttpEntity,java.lang.String)

就是content-typeString中返回的是什么?

相反,我用我的方法得到的值是在 String 中返回的值吗?

我认为这是第二个问题,但我对此不确定。而且,如果它是真的,这个值是如何存储到 String 中的?它们是用逗号还是一些特殊字符分隔的?

提前致谢!

一个HttpEntity表示HTTP响应正文的内容。 EntityUtils.toString(HttpEntity) 将该内容解释为 String 并 returns 给您。

如果您的 HTTP 响应是这样的

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: 80

<?xml version="1.0" encoding="utf-8"?>
<root>
    <nested attr="whatever" />
</root>

那么 EntityUtils.toString(HttpEntity) 返回的 String 将只包含

<?xml version="1.0" encoding="utf-8"?>
<root>
    <nested attr="whatever" />
</root>

注意 EntityUtils.toString 的默认字符集:

Get the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "ISO-8859-1" is used.

org.apache.http.util.EntityUtils.toString(response.getEntity, "UTF-8");