Search code examples
javaxmlxml-parsingsaxsaxparser

IOException - XML Parsing


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 ?


Solution

  • 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());