tags:

views:

305

answers:

3

Hi

Is anyone aware of a quick way of reading in an xml file over http? (e.g. i have a file located in http://www.abc.com/file.xml). How can i read this file from a java app

All help is greatly appreciated

Thanks Damien

+6  A: 

Use java.net.URL to get an InputStream:

final URL url = new URL("http://www.abc.com/file.xml");
final InputStream in = new BufferedInputStream(url.openStream());
// Read the input stream as usual

Exception handling and stuff omitted for brevity.

Dave Ray
Thanks for the solution dave, worked a treat
Damo
+2  A: 

Dave Ray's answer is indeed quick and easy, but it won't work well with HTTP redirects or if you for example have to go through a proxy server that requires authentication. Unfortunately, the standard Java API's classes (in java.net) lack some functionality or are hard to use in such circumstances.

The open source library Apache HttpClient can handle redirects automatically and make it easy to work with proxy servers that require authentication.

Here's a basic example:

HttpClient client = new HttpClient();
GetMethod method = new GetMethod("http://www.abc.com/file.xml");

int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
    System.err.println("Method failed: " + method.getStatusLine());
}

byte[] responseBody = method.getResponseBody();
Jesper
Thanks Jesper. The server that houses the xml is under my control so I dont have to worry about redirects. Thanks though for your valid input, its much appreciated
Damo
A: 

If you plan on using the W3C DOM and aren't interested in any of the IO or HTTP details you can do the following:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

...

final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document document = builder.parse("http://www.abc.com/file.xml");
laz