How to connect to a .NET Web Service from a J2ME MIDlet using kSOAP 2

8 comments - This post in romanian

Web services had and continue to have a great impact on the development of Web applications because they allow total independence between clients and service providers. The location, the platform, the programming language and the architecture of both the clients and the services has no effect on each other. The Internet technologies and standards that allowed the implementation of Web services are HyperText Transfer Protocol (HTTP), eXtensible Markup Language (XML), Remote Procedure Call (RPC), Web Services Description Language (WSDL), Simple Object Access Protocol (SOAP) and Universal Description, Discovery, & Integration (UDDI).

In this article we will see how to connect to a .NET Web Service from a j2ME MIDlet using kSOAP2 library. The Java 2 Micro Edition (J2ME) Platform offers support for Web Services through the J2ME Web Services API (WSA), JSR 172, which provides two optional APIs: remote service invocation (JAX-RPC) and XML parsing (JAXP). For the next example, we will use the third party kSOAP 2 library because it is lightweight and efficient. The solution is developed in the NetBeans IDE but you could use also Eclipse IDE.

In order to test the J2ME solution we will connect to a simple .NET Web Service that offers a method that adds two integers. If you are new to .NET Web Services you can get some info on the www.asp.net portal ([How Do I:] Create and Call a Simple Web Service in ASP.NET). The source code of the .NET Web Service, WebServiceExample.asmx, is:

namespace itcsolutions
{
 
    [WebService(Namespace = "http://www.itcsolutions.eu/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
 
    public class WebServiceExample : System.Web.Services.WebService
    {
 
        [WebMethod]
        public int add(int value1, int value2)
        {
            return value1 + value2;
        }
    }
}

 

1. Download the latest version of the kSOAP 2 library which is available on the project sourceforge page (http://sourceforge.net/projects/ksoap2/). At this moment, the archive of the kSOAP 2 library is ksoap2-j2me-core-2.1.2.jar

2. Open NetBeans and create a new J2ME project (J2ME tutorial – How to create a simple MIDlet application with NetBeans) with these properties:

  • Emulator Platform: Java Platform Micro Edition SDK 3.0
  • Device: DefaultCldcPhone1
  • Device Configuration: CLDC-1.1
  • Device Profile: MIDP-2.1

 

How to add the kSOAP 2 library to the J2ME project in NetBeans

3. Add the kSOAP 2 library to the MIDlet project:

How to add the kSOAP library in a J2ME project from NetBeans

How to add the kSOAP library in a J2ME project from NetBeans

3.1 Select the J2ME project in the Projects panel in NetBeans. Right-Click on project name and select Properties;

3.2 Select the Libraries & Resources category;

3.3 Click on the Add Jar/Zip… button and select the kSOAP 2 library (ksoap2-j2me-core-2.1.2.jar) downloaded at step 1;

3.4. Verify if the package is checked and click OK. 

 

4. Create a simple MIDlet ((J2ME tutorial – How to create a simple MIDlet application with NetBeans)with these properties:

  • MIDlet Name: MidletkSOAP
  • MIDP Class Name: MidletkSOAP
  • Package: eu.itcsolutions.j2me.ksoap

5. We will preserve the simplicity of the example and we will define an interface that has a Form with:

The UI of the kSOAP MIDlet example

The UI of the kSOAP MIDlet example

  • two TextField controls that will get the numeric values;
  • one StringItem to display the sum result;
  • one Exit command that will finish the MIDlet;
  • one Add command that will call the Web Service and display the sum result;

All UI controls are defined as attributes of the MidletkSOAP class and are initialized in the class constructor:

package eu.itcsolutions.j2me.ksoap;
 
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
 
public class MidletkSOAP extends MIDlet {
    //the main form
    Form mainForm = null;
    //the text-boxes for the input
    TextField txtBoxA = null;
    TextField txtBoxB = null;
    //the result label
    StringItem result = null;
    //the Exit command
    Command cmdExit = null;
    Command cmdAdd = null;
 
    //the Display reference
    Display display = null;
 
    public MidletkSOAP()
    {
        //construct the main form
        mainForm = new Form("kSOAP Example");
 
        //construct the controls
        txtBoxA = new TextField("Value 1:", null, 5, TextField.NUMERIC);
        txtBoxB = new TextField("Value 2:", null, 5, TextField.NUMERIC);
        result = new StringItem("Result:", null);
 
        //add controls to the form
        mainForm.append(txtBoxA);
        mainForm.append(txtBoxB);
        mainForm.append(result);
 
        //construct commands
        cmdExit = new Command("Exit", Command.EXIT, 1);
        cmdAdd = new Command("Add", Command.SCREEN, 1);
 
        //add commands
        mainForm.addCommand(cmdAdd);
        mainForm.addCommand(cmdExit);
    }
 
    public void startApp() {
    }
 
    public void pauseApp() {
    }
 
    public void destroyApp(boolean unconditional) {
    }
}
Important !
Do not forget that on the J2ME platform the mobile application display is controlled by a Display object (J2ME tutorial – How to create and display forms and alerts).

In the MIDlet startApp() method, that is called when the application is starting, we initialize the Display reference and display the previous form.

    public void startApp() {
        //get the Display reference
        if(display == null)
            display = Display.getDisplay(this);
        //display the main form
        display.setCurrent(mainForm);
    }

 

6. Because we want to use the Exit and Add commands we define the handler for the Command event by implementing the CommandListener interface and overriding the commandAction(Command c, Displayable d) abstract method:

    public void commandAction(Command c, Displayable d) {
        }
    }

7. Register the form as the command listener in the MidletkSOAP startApp() method:

        //register the command listener
        mainForm.setCommandListener(this);
Important !
Do NOT forget to register the listener. By implementing the CommandListener interface you only define a possible listener.

8. The Exit command will close the mobile application:

    public void commandAction(Command c, Displayable d) {
        if (c == cmdExit) {
            this.destroyApp(false);
            this.notifyDestroyed();
        }
    }

 

How to use kSOAP 2 to connect to a .NET Web Service from a J2ME MIDLet

The architecture of the solution is based on next activities:

The arhitecture of thr kSOAP MIDlet

The arhitecture of thr kSOAP MIDlet

  • the user insert the two values and select the Add command
  • the kSOAP library envelopes the values in a SOAP request and sends the message to the .NET Web Service; sending the request is the event that calls the remote method;
  • the application gets the SOAP response that contained the result returned by the remote method;
  • using the kSOAP library, the result is extracted from the response and it is displayed.

9. We define a new method, callWebServiceMethod(), that will encapsulates the kSOAP logic. The core of the kSOAP 2 library is represented by the SoapObject class which is used to manage SOAP requests and responses. The SOAP object is described by:

  • the Web Service namespace
  • the method name

In the callWebServiceMethod() we define two String constants, to store the SOAP object attributes values. With these two values we create the SOAP object:

//the kSOAP solution
    public void callWebServiceMethod() {
        String NAMESPACE = "http://www.itcsolutions.eu/";
        String METHOD_NAME = "add";
 
        //create a SOAP object
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    }

10. As we have seen in the .NET Web Service source code, it has the add(int a, int b) method, that receives two integer values as arguments. The method parameters are also encapsulated in the SOAP request using the addProperty() method:

        //add method arguments
        request.addProperty("value1",
                Integer.valueOf(txtBoxA.getString()));
        request.addProperty("value2",
                Integer.valueOf(txtBoxB.getString()));

11. In order to generate the XML based request we must use a SoapSerializationEnvelope (from org.ksoap2.serialization package) object. When we construct the SoapSerializationEnvelope we must decide which is the SOAP protocol version we want to use. For the .NET Web Service, from this example, we will use SOAP  1.1.

Because we are connecting to a .NET Web Service we set the .dotNet property of the SoapSerializationEnvelope object to true.

Also, the previous SoapObject object is set as the outbound message for the SOAP call.

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

12. The XML SOAP request is sent over HTTP using a HttpTransport (org.ksoap2.transport package)object. For the remote call we need the Web Service URL and the SOAP action (the Web Service namespace plus the method name).

        String SOAP_ACTION = "http://www.itcsolutions.eu/add";
        String URL = "http://localhost:50827/WebServiceExample.asmx";
 
        HttpTransport j2meHttpTransport = new HttpTransport(URL);

13. Once we get the SOAP response, we extract and display the result:

        try {
            //if you want to debug uncomment next line
            //j2meHttpTransport.debug = true;
            j2meHttpTransport.call(SOAP_ACTION, envelope);
            SoapObject content = (SoapObject) envelope.bodyIn;
            String sum = content.getProperty(0).toString();
 
            result.setText(sum);
        } catch (Exception e) {
            e.printStackTrace();
        }

14. The callWebServiceMethod() is called when the user selects the Add command:

    public void commandAction(Command c, Displayable d) {
        if (c == cmdExit) {
            this.destroyApp(false);
            this.notifyDestroyed();
        } else if (c == cmdAdd) {
            callWebServiceMethod();
        }
    }

 

The complete example of the kSOAP J2ME application is available in this complete solution file.

If you have problems with the examples or you don’t understand our explanations, put a question in the comments and we will help you. Also, any suggestion or comment that will improve this material is appreciated.

Like it? Then share this post or check the external adds. Sharing is the best way to appreciate the author.

, ,


  1. #1 by Princess on November 26th, 2011

    very usefull lesson
    thaaaaaaaaaaaaank you very much

  2. #2 by Amila thennakoon on December 14th, 2011

    Thank u a lot for post this … this is the lesson im looking for my Project

  3. #3 by Amila thennakoon on December 14th, 2011

    this is works for me also vb.net web service thanks a lot again

  4. #4 by RAJ on March 26th, 2012

    Thank you so much…
    Now my app run very well and me solve all above my problems and once again thanks for this such a nice tutorial.

  5. #5 by Aoshi on June 26th, 2012

    Thank you very much.

  6. #6 by ko thawdar on June 21st, 2013

    thank you so much. it is very useful.

  7. #7 by jignesh trivedi on November 22nd, 2013

    short and sweet lesson but very usefull
    i run both web service and j2me application
    run successfully
    thank you very much..

    please suggest more lesson if any advance like android…..

  8. #8 by Jevu on December 5th, 2013

    This has saved me hours of coding. Very useful tutorial
    Keep up the good work

(will not be published)

  1. No trackbacks yet.