我正在使用org.apache.commons.httpclient.HttpClient
,需要设置响应编码(由于某种原因,服务器在Content-Type中返回不正确的编码)。我的方法是将响应作为原始字节获取,并使用所需的编码转换为String
。我想知道是否有更好的方法来解决这个问题(例如设置HttpClient)。感谢您的建议。
我正在使用org.apache.commons.httpclient.HttpClient
,需要设置响应编码(由于某种原因,服务器在Content-Type中返回不正确的编码)。我的方法是将响应作为原始字节获取,并使用所需的编码转换为String
。我想知道是否有更好的方法来解决这个问题(例如设置HttpClient)。感谢您的建议。
我认为没有更好的方法使用 HttpClient
3.x API。
HTTP 1.1规范明确指出客户端“必须”遵守响应头中指定的字符集,并在未指定字符集时使用ISO-8859-1。 HttpClient
API的设计基于程序员想要遵守HTTP规范的假设。显然,您需要违反规范以便与不符合规范的服务器通信。尽管如此,这不是API设计人员明确支持的用例。
如果您使用的是 HttpClient
4.x,则可以编写自己的 ResponseHandler
将正文转换为 HttpEntity
,忽略响应消息的概念字符集。
Server serves data, so it's up to server to serve it in an appropriate format. So response encoding is set by server not client. However, client could suggest to server what format it would like via Accept and Accept-Charset:
Accept: text/plain
Accept-Charset: utf-8
However, http servers usually do not convert between formats.
If option 1. does not work, then you should look at the configuration of the server.
When String is sent as raw bytes (and it always is, because this is what networks transmit), there is always the encoding defined. Since server produces this raw bytes, it defines the encoding. So, you can not take raw bytes and use encoding of your choice to create a String. You must use encoding that was used when converted from String to bytes.
大家好,
万一有人通过谷歌搜索设置HttpClient以使用UTF-8编写的话,这篇文章可能会对你有所帮助。
这行代码应该很方便...
response.setContentType("text/html; charset=UTF-8");
最好的
Servlet
,因此没有HttpServletResponse
。 - michal.kreuzman.getEntity().getContent()
。这是一个纯字节流,因此如果您想忽略服务器告知的编码,可以简单地在其周围包装自己的InputStreamReader。
好的,看起来我使用了错误的版本(显然,有太多的HttpClient
类存在)。
但是和之前一样,只是位于其他类中: HttpMethod
有一个 getResponseBodyAsStream()
方法,你现在可以在其周围包装自己的 InputStreamReader。(或者一次获取整个数组,如果它不太大,并将其转换为字符串,就像你写的那样。)
我认为尝试更改响应并让 HttpClient 分析它并不是正确的方法。
我建议向服务器管理员/网站管理员发送关于错误字符集的消息。
HttpClient.getResponseBodyAsString()
从响应头中获取编码)。我已经尝试在请求头中设置Accept和Accept-Charset,但这并没有帮助我。显然,这是服务器上的问题,但我不是所有者,因此无法对其进行更改。 - michal.kreuzman