gpt4 book ai didi

java - Java HttpURLConnection 的编码错误

转载 作者:行者123 更新时间:2023-12-01 15:42:16 26 4
gpt4 key购买 nike

尝试从 MS Webservice 读取生成的 XML

URL page = new URL(address);
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
box.setText("Getting data ...");
String line;
do {
line = buff.readLine();
text.append(line + "\n");
} while (line != null);
box.setText(text.toString());

URL u = new URL(address);
URLConnection uc = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {

inputLine = java.net.URLDecoder.decode(inputLine, "UTF-8");
System.out.println(inputLine);
}
in.close();

除了 Web 服务输出之外,任何页面都可以正常读取它奇怪地读取大于和小于符号

它读作“<”和 > 到“>”不带空格,但如果我在这里输入不带空格的 stackoverflow 会使它们 < 和 >

请帮忙谢谢

最佳答案

首先,这一行似乎存在困惑:

inputLine = java.net.URLDecoder.decode(inputLine, "UTF-8");

这实际上表明您希望服务器提供的文档中的每一行都经过 URL 编码。 URL 编码与文档编码不同。

http://en.wikipedia.org/wiki/Percent-encoding

http://en.wikipedia.org/wiki/Character_encoding

看看你的代码片段,我认为 URL 编码(百分比编码)不是你想要的。

文档字符编码而言。您正在这一行进行转换:

InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());

conn.getContent() 返回一个对字节进行操作的 InputStream,而读取器对字符进行操作 - 字符编码转换在这里完成。查看 InputStreamReader 的其他构造函数,它将编码作为第二个参数。如果没有第二个参数,您将依赖于 java 中的平台默认值。

InputStreamReader(InputStream in, String charsetName)

例如,您可以将代码更改为:

InputStreamReader in = new InputStreamReader((InputStream) conn.getContent(), "utf-8");

但真正的问题是“您的服务器以什么编码提供内容?”如果您也拥有服务器代码,则可以将其硬编码为合理的内容,例如 utf-8。但如果它可能有所不同,您需要查看 http header Content-Type 来弄清楚。

String contentType = conn.getHeaderField("Content-Type");

contentType 的内容如下所示

text/plain; charset=utf-8

获取该字段的简便方法是:

String contentEncoding = conn.getContentEncoding();

请注意,完全有可能未提供任何字符集,或未提供 Content-Type header ,在这种情况下,您必须使用合理的默认值。

关于java - Java HttpURLConnection 的编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com