解析URL时,出现此错误:
[Fatal Error] :1:1: Content is not allowed in prolog
代码中应改进什么? 还有必需的链接。
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Main2 {
public static void main(String[] args) throws ParserConfigurationException, MalformedURLException {
String link = "https://samples.openweathermap.org/data/2.5/weather?q=London&appid=b6907d289e10d714a6e88b30761fae22";
URL url = new URL(link);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(url.openStream());
} catch (ParserConfigurationException | SAXException | IOException ex) {
ex.printStackTrace();
}
}
}
答案 0 :(得分:1)
请问您是否可以确定您提供的URL的确切响应类型,因为即使我将内容类型发送为“ application / xml”,我在浏览器和邮递员中也看到了Json响应类型。因此,请不要使用xml解析器来解析响应,因为您的响应是以JSON格式进行的。您需要使用json解析器来解析Json对象。