obtaining response charset of response to get or post request

人盡茶涼 提交于 2019-12-22 05:04:14

问题


I am working to extract response charset in a java web app, where I am using Apache HTTP Client.

For example, one possible value obtained from "Content-Type" header is

    text/html; charset=UTF-8

Then my code will extract all text after the "=" sign...

So the charset as extracted will be

    UTF-8

I just wanted to know, is the above method for obtaining response charset correct? Or is there some scenario where the above code will not work? Is there something I am missing here?


回答1:


Doesn't httpclient (or http core) already provide that functionality? Something like this:

HttpResponse response = ...
String charset = EntityUtils.getContentCharSet(response.getEntity());



回答2:


The method provided by forty-two can work. But the method is deprecated, I find out that this website has a good example of method to find the charset.

HttpEntity entity = response.getEntity();
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
System.out.println("Charset  = " + charset.toString());



回答3:


Well, that approach will fail when

  1. the charset value is quoted
  2. when the quoted value uses escapes
  3. when there are parameters other than "charset"


来源:https://stackoverflow.com/questions/9112259/obtaining-response-charset-of-response-to-get-or-post-request

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