简体   繁体   中英

Java IO Exception for DOMParser

I'm trying to parse an XML file in Java using the DOM parser with the following code:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);

And the last line (when calling the .parse() func) is giving the error:

java.io.IOException: Server returned HTTP response code: 403 for URL: http://testng.org/testng-1.0.dtd

How do I go about fixing this error?

Are you trying to access some URL in your code. HTTP 403 status code means access is forbidden, this can usually happen when user agent header is not set. You can set it as follows:

URLConnection connection = new URL("https://www.google.com/search?q=" + query).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

Please refer to this for more details.

It's trying to load testng-1.0.dtd , the DTD for your XML document.

Download it yourself from wherever you can get it, and configure the DocumentBuilder to look for it there by providing an EntityResolver to DocumentBuilder.setEntityResolver() .

Or else fix your HTTP proxy. The document itself is not authorization-protected, which is what the 403 means.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM