gpt4 book ai didi

java - 使用 URL.openStream (Java) 打开 url

转载 作者:行者123 更新时间:2023-11-30 04:14:18 27 4
gpt4 key购买 nike

我正在尝试从 openweatherapi 获取一些 xml,但当 url 包含 æ、ø 或 å 时出现问题。

失败的是:

URL website = new URL(params[0]);
InputStream inputStream = website.openStream(); // here it throws an FileNotFoundException
InputSource input = new InputSource(inputStream);

params[0] 可能是:http://api.openweathermap.org/data/2.5/weather?q =århus,&mode=xml&units=公制

整个代码是:

public class GetWeatherInfo extends AsyncTask<String, Integer, String> {

@Override
protected String doInBackground(String... params) {

String weatherInfo = null;

try {
URL website = new URL(params[0]);
InputStream inputStream = website.openStream();
InputSource input = new InputSource(inputStream);

SAXParserFactory saxp = SAXParserFactory.newInstance();
SAXParser sp = saxp.newSAXParser();
XMLReader xmlReader = sp.getXMLReader();

HandlingXMLStuff handler = new HandlingXMLStuff();
xmlReader.setContentHandler(handler);

xmlReader.parse(input);

weatherInfo = handler.info.dataToString();

} catch (Exception e) {
e.printStackTrace();
}
return weatherInfo;
}

最佳答案

您需要转义特殊字符。构造一个 URI 对象,然后使用 toASCIIString() 方法转义特殊字符。这可以按如下方式完成

    try {
String url = "http://api.openweathermap.org/data/2.5/weather?q=århus,&mode=xml&units=metric";
URI uri = new URI(url);
URL escapedUrl = new URL(uri.toASCIIString());
} catch (URISyntaxException e) {
// handle exception
} catch (MalformedURLException e) {
// handle exception
}

现在,这意味着在您的示例中,您可以执行以下操作:

URL website = new URL(new URI(params[0]).toASCIIString());

关于java - 使用 URL.openStream (Java) 打开 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783283/

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