Reputation: 5637
I am trying to parse an xml response from the below url -
http://imdbapi.org/?type=xml&q=argo
For this, i have written the below code -
try
{
XMLReader myReader = XMLReaderFactory.createXMLReader();
xmlHandler handlerobj = new xmlHandler();
myReader.setContentHandler(handlerobj);
myReader.parse(new InputSource(new URL("http://imdbapi.org/?type=xml&q=argo").openStream()));
}
catch(Exception e)
{
System.out.println("Error");
}
xmlHandler is a class that extends DefaultHandler. I am getting an IOException in the above code.
Stack trace -
java.io.IOException: Server returned HTTP response code: 403 for URL: http://imdbapi.org/?type=xml&q=argo
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at gui.getimdbdata(gui.java:73)
at gui.main(gui.java:64)
What is the problem with this code ?
Upvotes: 1
Views: 1263
Reputation: 5637
Solved the issue, thanks to @dijkstra !
The web service would only allow browser to fetch the xml data.
Following are the modifications -
url = new URL(urlString);
uc = url.openConnection();
uc.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
uc.connect();
uc.getInputStream();
BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
Upvotes: 0
Reputation: 112
You must set the user.agent:
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
(if you connect to the URL with your browser this is done automagically)
Upvotes: 2