【问题标题】:HttpsURLConnection and Charset for InputStreamReader?InputStreamReader 的 HttpsURLConnection 和字符集?
【发布时间】:2023-03-08 07:29:01
【问题描述】:

在下面的代码中:

HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("charset", "utf-8");

InputStream input = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(input, "utf-8");
BufferedReader buffer = new BufferedReader(reader);
...

InputStreamReader 是用 UTF-8 构造的,因为 setRequestPropertyHttpsURLConnection。但是,我认为代码确实需要从响应中获取CharSet。但这似乎是一个先有鸡还是先有蛋的问题。

是否可以检索服务器在其响应中实际使用的CharSet(而不是将其设置为我{wished|希望}的)?

【问题讨论】:

    标签: java character-encoding httpurlconnection inputstreamreader


    【解决方案1】:

    通常,您可以做的最好的事情是设置Accept-Charset 请求标头以指示您的客户端接受的字符编码。例如,

    Accept-Charset: UTF-8
    

    如果 HTTP 服务器配置正确,响应将是 UTF-8。响应 Content-Type 应包含响应的字符编码。

    【讨论】:

    • 谢谢@Sotirios。我认为这就是我对setRequestProperty 所做的事情。我关心的是配置错误的服务器。这就是为什么我想知道服务器实际响应的原因,以便我可以创建正确的InputStreamReader
    • @jww 您使用的是setRequestProperty,但设置了错误的标题。检查响应标头和正文以验证内容类型。
    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2013-01-07
    • 2012-07-14
    • 2011-05-21
    • 2012-08-25
    相关资源
    最近更新 更多