如何找到mimetype的响应

Arv*_*ind 11 java httpclient apache-httpcomponents

我正在处理使用Apache HTTP客户端发出的GET请求(v4-最新版本;而不是旧版本的v3)...

如何获取响应的mimetype?

在apache http客户端的旧v3中,使用以下代码获取mime类型 -

 String mimeType = response.getMimeType();
Run Code Online (Sandbox Code Playgroud)

如何使用apache http客户端的v4获取mimetype?

pep*_*red 31

要从响应中获取内容类型,您可以使用ContentType类.

HttpEntity entity = response.getEntity();
ContentType contentType;
if (entity != null) 
    contentType = ContentType.get(entity);
Run Code Online (Sandbox Code Playgroud)

使用此类,您可以轻松提取mime类型:

String mimeType = contentType.getMimeType();
Run Code Online (Sandbox Code Playgroud)

或者charset:

Charset charset = contentType.getCharset();
Run Code Online (Sandbox Code Playgroud)

  • 对于Android开发人员:Apache HTTP库的Android端口中没有ContentType类 (4认同)
  • 这听起来比接受的答案更好. (2认同)

Vla*_*lad 18

"Content-type"HTTP标头应该为您提供mime类型信息:

Header contentType = response.getFirstHeader("Content-Type");
Run Code Online (Sandbox Code Playgroud)

或者作为

Header contentType = response.getEntity().getContentType();
Run Code Online (Sandbox Code Playgroud)

然后你可以提取mime类型本身,因为内容类型也可以包括编码.

String mimeType = contentType.getValue().split(";")[0].trim();
Run Code Online (Sandbox Code Playgroud)

当然,在获取标头的值之前不要忘记进行空检查(如果服务器没有发送内容类型标头).