How to read XML response from a URL in java?
If you want to print XML directly onto the screen you can use TransformerFactory
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
TransformerFactory transformerFactory= TransformerFactory.newInstance();
Transformer xform = transformerFactory.newTransformer();
// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(System.out));
Get your response via a regular http-request, using:
- Apache HttpComponents
- the built-in
URLConnection con = new URL("http://example.com").openConnection()
;
The next step is parsing it. Take a look at this article for a choice of parser.
For xml parsing of an inputstream you can do:
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
But to communicate over http from server to client I prefer using hessian library or springs http invoker lib