gpt4 book ai didi

java - 尝试从 URL(在 Java 中)读取在某些情况下会产生乱码

转载 作者:行者123 更新时间:2023-11-29 08:15:26 27 4
gpt4 key购买 nike

我正在尝试读取 URL,然后打印结果。

BufferedReader in = new BufferedReader(
new InputStreamReader(new URL("http://somesite.com/").openStream(), "UTF-8"));
String s = "";
while ((s=in.readLine())!=null) System.out.println(s);
in.close();

它大部分时间都运行良好,并打印网站的源代码。然而,我的问题是,在特定的网站上,它会打印出乱码,而不是源代码,例如符号和其他不寻常的字符。

是否有一些因网站而异的属性会影响它的阅读方式?该页面在 Firefox 中加载得很好,我可以毫无问题地在那里查看源代码。如果 firefox 可以访问源代码,我应该也可以;我只是不确定为什么它不起作用...

编辑:将“UTF-8”添加到 InputStreamReader。所有奇怪的字符现在都是问号...仍然无法正常工作...

最佳答案

经过大量搜索,我找到了这个问题的答案。 xml 被读取为乱码,因为它是 Gzip 压缩的。读取它的方法是使用 GZIPInputStream。这是因为 XML 的压缩方式不同。

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip");
InputStreamReader in = new InputStreamReader (new GZIPInputStream(connection.getInputStream()));
String str;
while (true) {
int ch = in.read();
if (ch==-1) {
break;
}

关于java - 尝试从 URL(在 Java 中)读取在某些情况下会产生乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5188382/

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