Read xml file using http

Does anyone know a quick way to read in an XML file via http? (for example, I have a file located at http://www.abc.com/file.xml ). How can I read this file from a java application

All help is appreciated

Thanks Damien

+6
java xml
source share
3 answers

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.

+9
source

Dave Ray's answer is really quick and simple, but it will not work with HTTP redirects or if, for example, you have to go through a proxy server that requires authentication. Unfortunately, the standard Java API classes (in java.net) do not have some functionality or are difficult to use in such circumstances.

The open source Apache HttpClient library can automatically handle redirects and simplify work with proxies that require authentication.

Here is 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(); 
+3
source

If you plan to use the W3C DOM and are not interested in any of the IO or HTTP data, 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"); 
0
source

All Articles