This code snippet show you how to get the content type of a result of executing an Http Get request. TheContentType
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 HTTP Components Library which you can download from here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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("https://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("https://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); } } |
Eclipse Console Result:
1 2 3 4 5 |
MimeType = text/html Charset = UTF-8 MimeType = image/x-icon Charset = null |