jakub holý

building the right thing, building it right, fast

Sending a SOAP request to a Web Service via URLConnection

2006-05-25 04:15:13j2ee

You may want to test you web service by sending it a manually composed request and reading the XML returned. Here's how to do it (e.g. using BeanShell in jEdit):



The SOAP request

<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <getUserByEmail xmlns="http://service.w3.ibm.com">
      <iuser>jholy@example.com</iuser>
    </getUserByEmail>
  </soap:Body>
</soap:Envelope>

The Java code


String soapXml =   // jEdit: = buffer.getText(0,buffer.getLength())
java.net.URL url = new java.net.URL("http://localhost:9081/myServiceWAR/services/MyService");
java.net.URLConnection conn = url.openConnection();
// Set the necessary header fields
conn.setRequestProperty("SOAPAction", "http://localhost:9081/myServiceWAR/services/MyService");
conn.setDoOutput(true);
// Send the request
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(conn.getOutputStream());
wr.write(soapXml);
wr.flush();
// Read the response
java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) { System.out.println(line); /*jEdit: print(line); */ }