Saturday, July 28, 2007

How to REST?! - RESTing Without JAX-WS

During our example we used JAX-WS API to communicate with the web service. Although this is the best way, but there are other ways as well.One of these ways is using HttpURLConnection:

1. The client uses the URL.openConnection() method to create an instance of HttpURLConnection representing a connection to the Web service’s URL.

2. HttpURLConnection.connect() sends the HTTP GET request that has been configured using the Web service’s URL.

3. The Web service processes the request and writes the appropriate XML document to the HTTP response stream.

4. The HttpURLConnection’s InputStream is used to read the HTTP response’s XML document.

Exmaple of a non-JAX-WS Client

URL url = new URL(""); // the web service URL
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();InputStream in = con.getInputStream();

byte[] b = new byte[1024]; // 1K buffer

int result = in.read(b);
while (result != -1) {
System.out.write(b,0,result);
result =in.read(b);
}
in.close();
con.disconnect();

Note that the in this case the web service does not return the XML message directly in the StreamSource format but it writes the StreamSource result to the response OutputStream.

No comments: