This code snippet show you how to get the content type of a result of executing an Http Get request. The
ContentTypecan be obtained by using
ContentType.getOrDefault()method and passing an
HttpEntityas the arguments. The
HttpEntitycan be obtained from the
HttpResponseobject.
From the
ContentTypeobject 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.Charsetobject.
You need Apache HTTPComponents Library which you can download from here.
Another must reads:
- http://crunchify.com/how-to-send-http-request-and-capture-response-in-java/
- http://crunchify.com/simple-way-to-get-http-response-header-in-java/
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.