A J2ME client for the MapQuest web service

By: Anders Ohlsson

Abstract: A simple J2ME web service consumer

If you read my previous article on how to create a simple Java GUI client for a web service, then you know how easy it is to consume web services in JBuilder 7.

But what if you're travelling and don't want to carry around your laptop all the time? J2ME to the rescue!

We know from before, that we found the MapQuest web service at www.xmethods.com and that the URL for the WSDL is http://ww6.borland.com/webservices/MapQuest/MapQuest.exe/wsdl/IMapQuest.

Before we begin, we need to realize that the WebServices Pack for JBuilder isn't going to help us on small devices - it's too large. We need something smaller. We need kXML and kSOAP. If you don't already have them, go to www.ksoap.org and www.kxml.org and download them.

Now, if you fire up JBuilder 7, and if you have JBuilder MobileSet 3 installed, go ahead and start a new project (File | New Project). Make sure that you pick the micro edition of the JDK. Also add a new midlet (File | New... | Micro | Midlet).

You will also need to tell JBuilder about kXML and kSOAP. Do so by adding the two zip files on the required libraries tab in the project options for your project.

Go to the designer and add a stringitem to the display. This will be the component that shows us the directions when the application is running.

Now we need some code. Modify jbInit() so that it adds another button:

  addCommand(new Command("Exit", Command.EXIT, 1)); // This line is already there...
  addCommand(new Command("Hit me", Command.OK, 1));

Then modify the commandAction() event to look like:

  public void commandAction(Command command, Displayable displayable) {
    if (command.getCommandType() == Command.EXIT) {
      MIDlet1.quitApp();
    }
    if (command.getCommandType() == Command.OK) {
      try {
        SoapObject rpc = new SoapObject("urn:MapQuestIntf-IMapQuest", "GetDirections");

        rpc.addProperty("FromAddress", "39th and 11th");
        rpc.addProperty("FromCity", "New York");
        rpc.addProperty("FromState", "NY");
        rpc.addProperty("FromCountry", "US");
        rpc.addProperty("ToAddress", "1535 Broadway");
        rpc.addProperty("ToCity", "New York");
        rpc.addProperty("ToState", "NY");
        rpc.addProperty("ToCountry", "US");

        stringItem1.setText(""+new HttpTransport(
            "http://ww6.borland.com/webservices/MapQuest/MapQuest.exe/soap/IMapQuest",
            "urn:MapQuestIntf-IMapQuest#GetDirections").call (rpc));
      }
      catch (Exception e) {
        e.printStackTrace ();
      }
    }
  }

You're now ready to run the app. Hit Launch and then the button "Hit me". You should see something similar to this:


The running J2ME client

That's how easy it is to create a J2ME consumer for a web service in JBuilder 7. The code for this article can be found in CodeCentral.


Server Response from: ETNASC03