saxparserhttp-getgoogle-weather-api

How do I pass the result from httpget to SAX parser


I'm want to make a request to google API and pass the resulting XML to SAX parser here are both codes...

First the request:

HttpClient hclient = new DefaultHttpClient();   
HttpGet get = new HttpGet("http://www.google.com/ig/api?weather=Cardiff");

HttpResponse hrep = hclient.execute(get);
HttpEntity httpEntity = hrep.getEntity();

Then the parser:

SAXParserFactory saxpf = SAXParserFactory.newInstance();
SAXParser saxp = saxpf.newSAXParser();
XMLReader xr = saxp.getXMLReader();
ExHandler myHandler = new ExHandler();
xr.setContentHandler(myHandler);
xr.parse();

Is this the right way to do this and how do I connect both codes.

Thanks in advance


Solution

  • The SAXParser object can take in an input stream and the handler. So something like:

    SAXParser saxParser = factory.newSAXParser();
    XMLParser parser = new XMLParser();
    saxParser.parse(httpEntity.getContent(),parser);
    

    The getContent() method returns and input stream from the HttpRequest, and the XMLParser object is just a class I created (supposedly) that contains the definition of how to parse the XML.

    EDIT* You really should read the entire API for SAXParser, it has several overloaded methods:

    void parse(InputSource is, DefaultHandler dh) Parse the content given InputSource as XML using the specified DefaultHandler.

    void parse(InputSource is, HandlerBase hb) Parse the content given InputSource as XML using the specified HandlerBase.

    void parse(InputStream is, DefaultHandler dh) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.

    void parse(InputStream is, DefaultHandler dh, String systemId) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.

    void parse(InputStream is, HandlerBase hb) Parse the content of the given InputStream instance as XML using the specified HandlerBase.

    void parse(InputStream is, HandlerBase hb, String systemId) Parse the content of the given InputStream instance as XML using the specified HandlerBase.

    Some of the methods take an InputSource, some take an InputStream, as I stated earlier.