我正在尝试从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 = metric
整个代码是:
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;
}
答案 0 :(得分:2)
您需要转义特殊字符。构造一个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());