How to find mimetype of response

你说的曾经没有我的故事 提交于 2019-12-04 00:11:12

问题


I am working with a GET request made using Apache HTTP client (v4- the latest version; not the older v3)...

How do I obtain the mimetype of the response?

In the older v3 of apache http client, mime type was obtained using following code--

 String mimeType = response.getMimeType();

How do I get the mimetype using v4 of apache http client?


回答1:


A "Content-type" HTTP header should give you mime type information:

Header contentType = response.getFirstHeader("Content-Type");

or as

Header contentType = response.getEntity().getContentType();

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).




回答2:


To get content type from response you can use ContentType class.

HttpEntity entity = response.getEntity();
ContentType contentType;
if (entity != null) 
    contentType = ContentType.get(entity);

Using this class you can easily extract mime type:

String mimeType = contentType.getMimeType();

or charset:

Charset charset = contentType.getCharset();


来源:https://stackoverflow.com/questions/9077933/how-to-find-mimetype-of-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!