How do I get entity ContentType in HttpClient?

This code snippet show you how to get the content type of a result of executing an Http Get request. The ContentType can be obtained by using ContentType.getOrDefault() method and passing an HttpEntity as the arguments. The HttpEntity can be obtained from the HttpResponse object.

From the ContentType object we can get the mime-type by calling the getMimeType() method. This method will return a string value. To get the charset we can call the getCharset() method which will return a java.nio.charset.Charset object.

package org.kodejava.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClientBuilder;

import java.nio.charset.Charset;

public class EntityContentType {
    public static void main(String[] args) {
        EntityContentType demo = new EntityContentType();

    public void getContentType(String url) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
        } catch (IOException e) {

    private void showContentType(HttpEntity entity) {
        ContentType contentType = ContentType.getOrDefault(entity);
        String mimeType = contentType.getMimeType();
        Charset charset = contentType.getCharset();

        System.out.println("MimeType = " + mimeType);
        System.out.println("Charset  = " + charset);

The output of our code snippet are:

MimeType = text/html
Charset  = ISO-8859-1
MimeType = image/png
Charset  = null

Maven Dependencies

Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply