0

I am getting data from a REST based web service outputting data in XML format. As I am using DOM and later parsing it to a doc using the DocumentBuilder I am not able to get the server's HTTP Status Code if there is any error.

So, is it Possible to return the HTTP Status Code?

Here is a little snippet:

url = "MY_URL";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();

Any advice is much appreciable.
Thanks

beerBear
  • 939
  • 2
  • 16
  • 40

2 Answers2

3

You should do a bit changes in your code to do so:

URL url = new URL("MY_URL");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
Document doc = dBuilder.parse(new InputSource(connection.getInputStream()));
doc.getDocumentElement().normalize();
int code = connection.getResponseCode();
shem
  • 4,576
  • 2
  • 29
  • 43
  • Selvin had pointed the exact same in the comments..but as you're the first to put it here as "Answer". +1 :D – beerBear Apr 03 '13 at 07:38
1

url.openStream() will throw an IOException indicating the error if some problem occurs. Check the exception message/cause for details of the error.

Vegard
  • 4,372
  • 1
  • 18
  • 28