W3docs

How to call a SOAP web service on Android

To call a SOAP web service on Android, you can use the HttpURLConnection class to send an HTTP request to the web service and receive the response.

To call a SOAP web service on Android, you can use the HttpURLConnection class to send an HTTP request to the web service and receive the response. Note: Network operations must run on a background thread to avoid NetworkOnMainThreadException on Android. Here's an example of how you can do this:


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

String soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                   + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                   + "  <soap:Body>"
                   + "    <YourMethodName xmlns=\"http://tempuri.org/\">"
                   + "      <param1>value1</param1>"
                   + "      <param2>value2</param2>"
                   + "    </YourMethodName>"
                   + "  </soap:Body>"
                   + "</soap:Envelope>";

URL url = new URL("http://yourwebserviceurl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    connection.setRequestProperty("SOAPAction", "http://tempuri.org/YourMethodName");
    connection.setDoOutput(true);

    try (OutputStream os = connection.getOutputStream()) {
        os.write(soapRequest.getBytes(StandardCharsets.UTF_8));
        os.flush();
    }

    int responseCode = connection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        try (InputStream is = connection.getInputStream()) {
            // process the response
        }
    } else {
        // handle non-200 response codes
    }
} catch (IOException e) {
    // handle network failures
} finally {
    connection.disconnect();
}

In this example, the soapRequest variable contains the SOAP request message that will be sent to the web service. The request message includes the method name and the parameters that you want to pass to the web service.

You will need to replace "YourMethodName" and "http://tempuri.org/" with the actual method name and namespace of the web service, and replace "value1" and "value2" with the actual values for the parameters. You will also need to replace "http://yourwebserviceurl" with the actual URL of the web service.

For modern Android development, consider using established libraries like OkHttp or Retrofit, which handle background threading, connection pooling, and XML parsing more efficiently.

I hope this helps! Let me know if you have any questions.