Question

I am working with a GET request made using Apache HTTP client (v4- the latest version; not the older v3)...

How do I obtain the mimetype of the response?

In the older v3 of apache http client, mime type was obtained using following code--

 String mimeType = response.getMimeType();

How do I get the mimetype using v4 of apache http client?

Was it helpful?

Solution

A "Content-type" HTTP header should give you mime type information:

Header contentType = response.getFirstHeader("Content-Type");

or as

Header contentType = response.getEntity().getContentType();

Then you can extract mime type itself as the content-type may include encoding as well.

String mimeType = contentType.getValue().split(";")[0].trim();

Of course, don't forget about null-check before getting value of the header (in case the content-type header is not sent by server).

OTHER TIPS

To get content type from response you can use ContentType class.

HttpEntity entity = response.getEntity();
ContentType contentType;
if (entity != null) 
    contentType = ContentType.get(entity);

Using this class you can easily extract mime type:

String mimeType = contentType.getMimeType();

or charset:

Charset charset = contentType.getCharset();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top