1

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?

user207421
  • 289,834
  • 37
  • 266
  • 440
user2963365
  • 71
  • 3
  • 8

2 Answers2

1

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.

Mikaal Anwar
  • 1,630
  • 5
  • 16
  • i'm not trying to access any URLs in the code, so I'm guessing the error has something to do with one of the packages but I'm not sure how to fix it – user2963365 May 30 '18 at 23:45
  • @user2963365 You should examine the stack trace of the error to arrive at the line number sending this request to the above-mentioned URL. – Mikaal Anwar May 30 '18 at 23:50
1

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.

user207421
  • 289,834
  • 37
  • 266
  • 440