Java如何在HttpClient中获取实体ContentType?

此代码段向您展示如何获取执行Http Get请求的结果的内容类型。在ContentType可以通过使用获得的ContentType.getOrDefault()方法以及使HttpEntity作为参数。在HttpEntity可以从获得HttpResponse的对象。

从ContentType对象中,我们可以通过调用getMimeType()方法获得mime类型。此方法将返回一个字符串值。为了获得字符集,我们可以调用getCharset()将返回一个java.nio.charset.Charset对象的方法。

package org.nhooo.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.io.IOException;
import java.nio.charset.Charset;

public class EntityContentType {
    public static void main(String[] args) {
        EntityContentType demo = new EntityContentType();
        demo.getContentType("http://www.google.com");
        demo.getContentType("http://www.google.com/images/srpr/logo3w.png");
    }

    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();
            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("MimeType = " + mimeType);
        System.out.println("Charset  = " + charset);
    }
}

我们的代码片段的输出是:

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

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.9/httpclient-4.5.9.jar -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>

Maven中央