如何从响应中找到HTTP媒体类型(MIME类型)? [英] How to find HTTP Media Type (MIME type) from response?
问题描述
使用Apache HTTP Client v4发出 GET
请求时,如何获取响应媒体类型(正式为MIME类型)?
While issuing a GET
request using Apache HTTP Client v4, how do I obtain the response media type (formally MIME type)?
使用Apache HTTP Client v3,可以通过以下方式获得MIME类型:
Using Apache HTTP Client v3, the MIME type was obtained with:
String mimeType = response.getMimeType();
如何使用Apache HTTP Client v4获取媒体类型?
How do I get the media type using Apache HTTP Client v4?
推荐答案
"Content-type" HTTP标头应为您提供mime类型信息:
A "Content-type" HTTP header should give you mime type information:
Header contentType = response.getFirstHeader("Content-Type");
或为
Header contentType = response.getEntity().getContentType();
然后,您可以提取mime类型本身,因为content-type可能还包含编码.
Then you can extract mime type itself as the content-type may include encoding as well.
String mimeType = contentType.getValue().split(";")[0].trim();
当然,在获取标头的值之前,请不要忘记进行空检查(以防内容类型标头不是由服务器发送).
Of course, don't forget about null-check before getting value of the header (in case the content-type header is not sent by server).
这篇关于如何从响应中找到HTTP媒体类型(MIME类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!