Search code examples
javahttpclientapache-httpcomponents

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


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?


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