Matter faced during integration project

Wednesday, March 3, 2010

Sending SOAP request with JDK library



private static synchronized
String sendSOAPRequest(String soapMsg, String webserviceMethod, String soap_Endpoint) throws Exception {
try {
URL url = new URL(soap_Endpoint);
// setup HTTP Connecten to the service
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);

// create SOAP Request
connection.setUseCaches(false);
connection.setRequestProperty("Content-type", "text/xml; charset=iso-8859-1");
connection.setRequestProperty("SOAPAction", webserviceMethod);
System.out.println("SOAP-Endpoint: " + url);
System.out.println("SOAP-Action: " + webserviceMethod);

// send SOAP-Request
byte[] bytes = soapMsg.getBytes();
connection.setRequestProperty("Content-length", String.valueOf(bytes.length));
OutputStream out = connection.getOutputStream();
out.write(bytes);
out.close();

// read SOAP-response
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
if (connection.getResponseCode() == 500)
in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
else
throw e;
}
// handle the SOAP response
StringBuffer in_buffer = new StringBuffer(8192);
String temp = "";
while ((temp = in.readLine()) != null) {
in_buffer.append(temp);
}
in.close();
return in_buffer.toString();
} catch (Exception e) {
System.out.println("!!! Exception: " + e);
throw e;
}
// return "";
}