Anton Styopin Anton Styopin - 4 months ago 15
Java Question

MalformedURLException Java get XML from Server

I have following problem:

try {
String uri = "http://servername/ReportServer?%2fCool%Page&rs:Command=Render&rs:Format=XML&mandantId=2000";
URL url = new URL(uri);

URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer xform = tFactory.newTransformer();

xform.transform(new DOMSource(doc), new StreamResult(System.out));
} catch (Exception e) {
e.printStackTrace();
}


Now I get

java.net.MalformedURLException: no protocol: servername/ReportServer?%2fCool%Page&rs:Command=Render&rs:Format=XML&mandantId=2000


I want to get the xml content in java. If I type the url into the browser I get the xml as a download. I don't know why I get this error. Someone know how to solve this problem?

Answer

You forgot to define the protocol in your URL.

Protocol handlers for the following protocols are guaranteed to exist on the search path :-

 http, https, ftp, file, and jar

From Java API documentation for URL : http://docs.oracle.com/javase/7/docs/api/java/net/URL.html

public URL(String spec)
    throws MalformedURLException

Creates a URL object from the String representation. This constructor is equivalent to a call to the two-argument constructor with a null first argument.

Parameters:

  • spec - the String to parse as a URL.

Throws:

  • MalformedURLException - if no protocol is specified, or an unknown protocol is found, or spec is null.

You should have something like (example with HTTP) :

String uri = "http://servername/ReportServer?%2fCool%Page&rs:Command=Render&rs:Format=XML&mandantId=2000";

EDIT

You forgot to read the stream of your URL connection.

Here's an example :

URL url = new URL(u);

// Connecting to Webservice
URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder buffer = new StringBuilder();

// Reading
while ((inputLine = in.readLine()) != null) {
    buffer.append(inputLine);
}

// Closing the connection
in.close();
Comments