Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly returns EntityUtils.toString(response)?

I'm doing my API REST and I saw that in a lot of examples people use EntityUtils.toString(response) to get their response into a String from their GET, POST, PUT and DELETE 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 this String returns. I saw it into the official documentation.

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)

It is the content-type what is returned in the String?

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!

like image 796
Francisco Romero Avatar asked Mar 15 '23 20:03

Francisco Romero


2 Answers

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>
like image 163
Sotirios Delimanolis Avatar answered Mar 23 '23 04:03

Sotirios Delimanolis


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");

like image 30
Christophe Roussy Avatar answered Mar 23 '23 04:03

Christophe Roussy