gpt4 book ai didi

java - 解析 Web 服务响应时出现 MalformedURLException

转载 作者:数据小太阳 更新时间:2023-10-29 02:22:25 28 4
gpt4 key购买 nike

所以我正在尝试编写一个获取当前天气的简单网络服务。使用以下代码可以调用 Web 服务方法并将返回的 XML 数据打印到控制台。

但是,当我尝试解析此方法响应时,我得到了 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);

最佳答案

替换

xmlReader.parse(data);

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

您不小心调用了 SAXReader.parse 的错误重载。采用字符串的版本需要一个 URI,它可以在其中检索要解析的内容,而不是内容本身。

关于java - 解析 Web 服务响应时出现 MalformedURLException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11461738/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com