How to find HTTP Media Type (MIME type) from response?

27,077

Solution 1

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).

Solution 2

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();
Share:
27,077
Arvind
Author by

Arvind

Updated on December 30, 2020

Comments

  • Arvind
    Arvind over 3 years

    While issuing a GET request using Apache HTTP Client v4, how do I obtain the response media type (formally MIME type)?

    Using Apache HTTP Client v3, the MIME type was obtained with:

     String mimeType = response.getMimeType();
    

    How do I get the media type using Apache HTTP Client v4?

  • gardarh
    gardarh over 9 years
    For Android developers: The ContentType class is not available in the Android port of the Apache HTTP library
  • Admin
    Admin over 9 years
    For Android I guess one can use developer.android.com/reference/org/apache/http/message/… , the related parser class.
  • ymonad
    ymonad over 8 years
    I cannot understand why response.getEntity().getContentType() does not return ContentType instance.