2012-07-12 32 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