URLConnection 未获取字符集
我正在使用 URL.openConnection()
从服务器下载某些内容。服务器显示
Content-Type: text/plain; charset=utf-8
But connection.getContentEncoding()
returns null
。怎么了?
I'm using URL.openConnection()
to download something from a server. The server says
Content-Type: text/plain; charset=utf-8
But connection.getContentEncoding()
returns null
. What up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从
URLConnection.getContentEncoding()
返回的值返回来自Content-Encoding
标头的值URLConnection.getContentEncoding()
相反,而是执行
connection.getContentType()
用于检索 Content-Type 并从 Content-Type 中检索字符集。我已经包含了有关如何执行此操作的示例代码......The value returned from
URLConnection.getContentEncoding()
returns the value from headerContent-Encoding
Code from
URLConnection.getContentEncoding()
Instead, rather do a
connection.getContentType()
to retrieve the Content-Type and retrieve the charset from the Content-Type. I've included a sample code on how to do this....这是记录的行为,因为指定
getContentEncoding()
方法返回Content-Encoding
HTTP 标头的内容,而您的示例中未设置该标头。您可以使用 getContentType() 方法并自行解析结果字符串,或者可能寻求更多 高级 HTTP 客户端库,例如 Apache。This is documented behaviour as the
getContentEncoding()
method is specified to return the contents of theContent-Encoding
HTTP header, which is not set in your example. You could use thegetContentType()
method and parse the resulting String on your own, or possibly go for a more advanced HTTP client library like the one from Apache.正如@Buhake Sindi 的答案的补充。如果您使用 Guava,您可以执行以下操作而不是手动解析:
Just as an addition to the answer from @Buhake Sindi. If you are using Guava, instead of the manual parsing you can do: