gpt4 book ai didi

java - XML 解析期间字母显示不正确

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:34 28 4
gpt4 key购买 nike

我正在尝试解析网站:http://www.cbr.ru/scripts/XML_daily.asp

SAXParserFactory factory = SAXParserFactory.newInstance ();
Parserhandler handler = new Parserhandler ();
SAXParser parser = factory.newSAXParser ();
InputSource is = new InputSource ( "http://www.cbr.ru/scripts/XML_daily.asp");
is.setEncoding ( "iso-8859-1");
parser.parse (is, handler);

一般来说,我会尝试不同的编码 utf-8、Cp1251 等变体。

但作为返回,我得到如下字符:

Þæíîàôðèêàíñêèõ ðýíäîâ

或者我收到错误

unknown encoding

请帮帮我。

最佳答案

也许您可以得到正确的字符,如下所示。

public void theMethod() {
try {
String uri = "http://www.cbr.ru/scripts/XML_daily.asp";

ByteArrayInputStream bis = getByteArrayInputStreamOfUri(uri);
parser.parse(bis, handler);
} catch (...) {}
}

public ByteArrayInputStream getByteArrayInputStreamOfUri(String uri) {
InputStream is = getInputStreamOfUrl(uri);
if (is == null) {
return null;
}

Scanner sc = new Scanner(is, "Windows-1451");
StringBuilder sb = new StringBuilder();

while (sc.hasNextLine()) {
sb.append(sc.nextLine());
}

try {
return new ByteArrayInputStream(sb.toString().getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
return null;
}
}

private InputStream getInputStreamOfUrl(String uri) {
try {
URL url = new URL(uri);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
return connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

关于java - XML 解析期间字母显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40400801/

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