Damien
Damien

Reputation: 4121

read xml file using http

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

Upvotes: 6

Views: 6338

Answers (3)

laz
laz

Reputation: 28638

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");

Upvotes: 0

Jesper
Jesper

Reputation: 206946

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

Upvotes: 3

Dave Ray
Dave Ray

Reputation: 40005

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.

Upvotes: 9

Related Questions