2012-07-12 47 views
3

因此,我正在尝试编写一个获取当前天气的简单Web服务。使用以下代码可以调用Web服务方法,并将返回的XML数据打印到控制台。解析网络服务响应时出现MalformedURLException

但是,当我尝试解析此方法响应时,我得到MalformedURLException。我可以看到我想解析错误的XML。

于是,我就保存到文件的响应来分析这样的说法:

当我尝试保存网页响应文件我得到的所有中国字母。 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); 

回答

6

更换

xmlReader.parse(data); 

InputSource source = new InputSource(new StringReader(data)); 
xmlReader.parse(source); 

你不小心调用SAXReader.parse的错误超载。接受String的版本需要一个可以检索要解析的内容的URI,而不是内容本身。

+0

非常感谢您的快速和正确的回复。这解决了我的问题! – 2012-07-12 22:58:51

+0

不客气。为了将来的参考,你可以标记答案“接受”。这意味着“谢谢你,它的工作”。这个想法是,问题和答案自己说话,未来的访问者只需要问题和答案,而不是讨论。 – 2012-07-12 23:02:22