Saturday 11 February 2012

Invoke webservice in java

To invoke WebService in java without any WS library, just using HttpURLConnection you can act like here:
   URL url = new URL(address);
   HttpURLConnection rc = (HttpURLConnection) url.openConnection();
   rc.setRequestMethod("POST");
   rc.setDoOutput(true);
   rc.setDoInput(true);
   rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
   int len = soapEnvelope.length();
   rc.setRequestProperty("Content-Length", Integer.toString(len));
   rc.setRequestProperty("SOAPAction", soapAction);
   rc.connect();
   OutputStreamWriter out = new OutputStreamWriter(
     rc.getOutputStream());
   out.write(soapEnvelope, 0, len);
   out.flush();
   InputStreamReader read = new InputStreamReader(rc.getInputStream());
   StringBuilder returns = new StringBuilder();
   int ch = read.read();
   while (ch != -1) {
    returns.append((char) ch);
    ch = read.read();
   }
   read.close();
   rc.disconnect();

No comments: