所以我正在尝试编写一个简单的Web服务来获取当前的天气.使用以下代码,可以调用Web服务方法,并可以将返回的XML数据打印到控制台.
但是,当我尝试解析此方法响应时,我得到MalformedURLException.我可以看到我想在错误中解析的XML.
所以我尝试将响应保存到文件中以解析它:
当我尝试将Web响应保存到文件时,我会收到所有中文字母.System.out.println将XML完美地打印到控制台,就像我需要它在文件中一样.
我是一个新手,所以请原谅我,如果我错过了一些非常简单的事情.我想这样做而不必在本地保存文件,但无论什么工作都很好.
我的问题出在这段代码中:
GlobalWeather service = new GlobalWeather();
GlobalWeatherSoap port = service.getGlobalWeatherSoap();
String data = port.getWeather(city, country);
// this prints the xml response to the console perfectly
System.out.println(data);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new WeatherApp());
// this gives MalformedURLexception when set up this way.
// this gives the correct output when passed a locally stored XML file
// I have omitted my SAX methods and my weather class that holds the data
// but all work fine when using a local XML file on my machine.
xmlReader.parse(data);
Run Code Online (Sandbox Code Playgroud)
更换
xmlReader.parse(data);
Run Code Online (Sandbox Code Playgroud)
同
InputSource source = new InputSource(new StringReader(data));
xmlReader.parse(source);
Run Code Online (Sandbox Code Playgroud)
您无意中调用了错误的SAXReader.parse重载.采用String的版本需要一个URI,它可以检索要解析的内容,而不是内容本身.
| 归档时间: |
|
| 查看次数: |
538 次 |
| 最近记录: |