What exactly returns EntityUtils.toString(response)?
Solution 1
An HttpEntity
represents the content of the body of an HTTP response. EntityUtils.toString(HttpEntity)
interprets that content as a String
and returns it to you.
If your HTTP response is something like this
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>
Then the String
returned by EntityUtils.toString(HttpEntity)
will simply contain
<?xml version="1.0" encoding="utf-8"?>
<root>
<nested attr="whatever" />
</root>
Solution 2
Beware the default charset of 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");
Francisco Romero
The best way to learn something is trying to help others to solve their issues that you have never tried before. This is the reason why I am in Stackoverflow. Now starting with web developing.
Updated on June 04, 2022Comments
-
Francisco Romero almost 2 years
I'm doing my API REST and I saw that in a lot of examples people use
EntityUtils.toString(response)
to get theirresponse
into aString
from theirGET
,POST
,PUT
andDELETE
methods. Similar to this:HttpGet method = new HttpGet(url); method.setHeader("content-type", "application/json"); HttpResponse response = httpClient.execute(method); String responseString = EntityUtils.toString(response.getEntity());
PLEASE AVOID ANSWERS THAT SAID TO ME THAT IT GIVES TO ME A STRING
I know that it returns to me a
String
with the content of an entity (in this case the response) but here is where my doubts come, because I'm not secure about what thisString
returns. I saw it into the official documentation.Read the contents of an entity and return it as a String.
It is the
content-type
what is returned in theString
?On the contrary, are the values that I'm getting with my method what are returned in the
String
?I think it is the second one question but I'm not secure about that. And, in the case it is true, how this values are stored into the
String
? Are they separated by comas or some special character?Thanks in advance!
-
Francisco Romero almost 9 yearsSo, the String ignores the header of the HTTP response? Just the values inside?
-
Sotirios Delimanolis almost 9 years@Error404 An HTTP response has a status line, a list of headers, and a body. The content of the
HttpEntity
is just the body of the HTTP response. -
Francisco Romero almost 9 yearsSo I suppose that
Content-type
andContent-Length
are the headers andHTTP/1.1 200 OK
the status line, right? I'm sorry but I'm really new at this.