Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

Java: How to Get Entity ContentType in HttpClient?

$
0
0

http response header- Crunchify Tips

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.

You need Apache HTTPComponents Library which you can download from here.

Another must reads:

package com.crunchify.tutorials;

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.DefaultHttpClient;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author Crunchify.com
 */

public class CrunchifyGetHTTPContentType {
    public static void main(String[] args) {
    	CrunchifyGetHTTPContentType demo = new CrunchifyGetHTTPContentType();
        demo.requestCrunchifyPage();
        demo.requestCrunchifyLogo();
    }

    public void requestCrunchifyPage() {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://crunchify.com");
        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            showContentType(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void requestCrunchifyLogo() {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://crunchify.com/favicon.ico");
        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            showContentType(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

        System.out.println("\nMimeType = " + mimeType);
        System.out.println("Charset  = " + charset);
    }

}

Output:

MimeType = text/html
Charset  = UTF-8

MimeType = image/x-icon
Charset  = null

List of all Java Examples which you may be interested in.

The post Java: How to Get Entity ContentType in HttpClient? appeared first on Crunchify.


Viewing all articles
Browse latest Browse all 1037

Trending Articles