1

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

失败的是:

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

参数 [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;
    }
4

1 回答 1

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());
于 2013-09-13T10:00:07.910 回答