Friday, September 7, 2012

Java code to retrieve the node data from a XML string received from a web URL

Java code to retrieve the node data from a XML string received from a web URL:

Code:

import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class HttpRequestCode {
    public HttpRequestCode() {
        super();
    }

    public static void getResponse(String city) {

        HttpURLConnection connection = null;
       
        String url="http://feeds.feedburner.com/burrp/"+city+"-events/weekend?format=xml";

        try {
            connection =
                    (HttpURLConnection)new URL(url).openConnection();
            connection.setRequestProperty("content-type",
                                          "text/xml;charset=utf-8");
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(true);

            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
           
            rd.close();
           
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setNamespaceAware(false);
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            InputStream is1 = new ByteArrayInputStream(response.toString().getBytes());
            Document doc = docBuilder.parse (is1);
            doc.getDocumentElement ().normalize ();
            NodeList listOfChannels = doc.getElementsByTagName("description");
            String description=listOfChannels.item(1).getFirstChild().getNodeValue();
            System.out.println(description);

        } catch (FileNotFoundException e) {
           
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static void main(String[] args) {

        getResponse("Chennai");

    }
}

No comments:

Post a Comment