SoFunction
Updated on 2025-03-11

Sample code for calling WebService using ksoap2 in Android

When I was working last year, my first project was to access WebService. Since I have never been exposed to it, I have checked a lot of information and modified it slightly based on other people's code, and finally met my own needs. Recently, when I was sorting out my computer, I found this WebService access class. I was afraid that I would not find it when I needed it one day, so I simply wrote it on the blog to provide a reference for those in need.

1. Download the jar file of ksoap2

Download address:ksoap2-android-assembly-3.6.

After the download is completed, just rely on your own project.

2. Encapsulate network access tool class

I posted the code directly, and the comments were written in detail and modified according to my needs.

/**
  * Tool classes to access WebService
  */
public class WebServiceUtil {

 // Namespace private static final String NAMESPACE = "your namespace";
 // WebService server address private static final String ENDPOINT = "your address";

 // Generally, identity verification is required for development of your own company // Authentication method name private static final String ID_HEADERNAME = "verify method";
 // Authentication key private static final String ID_NAME_PARAM = "verify key1";
 // Authentication value private static final String ID_NAME_VALUE = "verify value1";
 // Authentication key private static final String ID_PASSWORD_PARAM = "verify key2";
 // Authentication value private static final String ID_PASSWORD_VALUE = "verify value2";

 // Is the accessed server developed by dotNet public static boolean isDotNet = true;

 // The size of the thread pool private static int threadSize = 5;
 // Create a thread pool with a fixed number of reusable threads to run these threads in a shared unbounded queue private static ExecutorService threadPool = (threadSize);

 // Connection response label public static final int SUCCESS_FLAG = 0;
 public static final int ERROR_FLAG = 1;

 /**
   * Calling the WebService interface
   *
   * @param methodName The call method name of the WebService
   * @param mapParams The parameter set of WebService can be null
   * @param reponseCallBack Server response interface
   */
 public static void call(final String methodName, SimpleArrayMap<String, Object> mapParams, final ResponseCallBack reponseCallBack) {

  // Create an HttpTransportSE object and pass the WebService server address  final HttpTransportSE transport = new HttpTransportSE(ENDPOINT);
   = true;

  // Authentication (if required)  Element[] header = new Element[1];
  // Pass the name of the namespace and verification method  header[0] = new Element().createElement(NAMESPACE, ID_HEADERNAME);
  // Create parameter 1  Element userName = new Element().createElement(NAMESPACE, ID_NAME_PARAM);
  (, ID_NAME_VALUE);
  header[0].addChild(, userName);
  // Create parameter 2  Element password = new Element().createElement(NAMESPACE, ID_PASSWORD_PARAM);
  (, ID_PASSWORD_VALUE);
  header[0].addChild(, password);

  // Create SoapObject object to pass request parameters  final SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
  // Add parameters  if (mapParams != null) {
   for (int index = 0; index < (); index++) {
    String key = (index);
    // In most cases, the passed parameters are of String type, but in few cases there is a boolean type, so use Object instead    Object value = (key);
    (key, value);
   }
  }

  // Instantiate SoapSerializationEnvelope, pass the version number of the SOAP protocol that enters the WebService  // Here are three versions of VER10 VER11 VER12, fill in according to your needs  final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
   = header; // Authentication (if required)   = isDotNet; // Set whether the .Net-developed WebService is called   = soapObject; // Pass parameters  //(soapObject);// is equivalent to the previous sentence
  // Handler used to communicate with the main thread  final Handler responseHandler = new Handler() {

   @Override
   public void handleMessage(Message msg) {
    (msg);
    // Determine which interface to call based on the arg1 value of the message    if (msg.arg1 == SUCCESS_FLAG) {
     ((String) );
    } else {
     ((Exception) );
    }
   }

  };

  // Submit a child thread to the thread pool and call WebService within this line  if (threadPool == null || ()) {
   threadPool = (threadSize);
  }
  (new Runnable() {

   @Override
   public void run() {
    String result = null;
    try {
     // Solve EOFException     ("", "false");
     // Connect to the server, some services may not need to pass NAMESPACE + methodName, and pass null for the first parameter.     (null, envelope);
     if (() != null) {
      // Get the SoapObject returned by the server response      SoapObject object = (SoapObject) ;
      result = (0).toString();
     }
    } catch (IOException e) {
     // When the first parameter of the call method is null, there will be a certain concept thrown IO exception.     // Therefore, you need to catch this exception and reconnect with the namespace plus the method name as parameter     // ();
     try {
      (NAMESPACE + methodName, envelope);
      if (() != null) {
       // Get the SoapObject returned by the server response       SoapObject object = (SoapObject) ;
       result = (0).toString();
      }
     } catch (Exception e1) {
      // ();
      ((0, ERROR_FLAG, 0, e1));
     }
    } catch (XmlPullParserException e) {
     // ();
     ((0, ERROR_FLAG, 0, e));
    } finally {
     // Send the retrieved message to the main thread using the Handler     ((0, SUCCESS_FLAG, 0, result));
    }
   }
  });
 }

 /**
   * Set the size of the thread pool
   *
   * @param threadSize
   */
 public static void setThreadSize(int threadSize) {
   = threadSize;
  ();
  threadPool = ();
 }

 /**
   * Server response interface, and this interface needs to be called back after response
   */
 public interface ResponseCallBack {

  void onSuccess(String result);

  void onError(Exception e);
 }

}

3. Use in Activity

private void request() {
  SimpleArrayMap<String, Object> map = new SimpleArrayMap<>();
  ("key1", "value1");
  ("key2", "value2");
  ("method name", map, new () {
   @Override
   public void onSuccess(String result) {
    // Request succeeded   }

   @Override
   public void onError(Exception e) {
    // Request failed   }
  });
 }

The call ends now. If you need to access the WebService, you can refer to it.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.