Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

MIDP Networking - web server and MIDlet interaction with example

From Wiki
Jump to: navigation, search
Article Metadata
Code ExampleTested with
SDK: S60 3rd Edition FP 1 SDK emulator, Nokia SDK 1.1 for Java
Devices(s): N97, X3-02
Created: Maveric (03 Jun 2010)
Last edited: hamishwillee (25 Jul 2013)

The purpose of this article is to show how to connect to a web server, pass information to it and parse response received. The example in this article will construct a URI with reference to a server side PHP script and passing values to it. It is the responsibility of the server-side script to process them further and return the result back for the MIDlet to display.



Network connections in J2ME are always established using the Connector class, regardless of the connection type. Methods are all static in the Connector class, and most important one is the open() method. In this article we will be using

static Connection open(String name) throws IOException

The connection string in the example in this article will be HTTP, adhering to the standard Uniform Resource Indicator (URI) syntax. As a result of using the opening method above, we do not implement any mode parameter and therefore the READ_WRITE mode is used by default.

As a result, the open() method will return an object of type Connection, acting as the base interface for rest of the connection interfaces. Using specific connection interface needs casting the Connection interface returned by open() to the appropriate type.

The example in this article will construct a URI with reference to a server side PHP script and passing values to it. It is the responsibility of the server-side script to process them further and return the result back for the MIDlet to display.


  • Web server with sufficient user rights and PHP support configured (localhost or remote).
  • J2ME (MIDP 2.0) supported phone device.

Example MIDlet - BMIcalc

In this example we will calculate Wikipedia BMI (Body Mass Index). The MIDlet will ask the user to first select either Metric (default) or Imperial set of measure. Then the user is to enter his/hers weight and height. The application will start the connect procedure when user presses the "Calculate it!" soft-button. The MIDlet will request the appropriate network access permissions from the user. If user accepts the connection request, the MIDlet will try attempting to issue the URL string added with the user input towards the web server.

For packaging and building the MIDlet use your favorite J2ME development tool. You can test the MIDlet with e.g. S60 3rd Edition FP 1 SDK emulator (remember to check your network connection settings). You may rename the MIDlet how you like, but remember to do all the required changes elsewhere too. The complete project can be download from here.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BMIcalc extends MIDlet implements ItemStateListener, CommandListener {
private Display myDisplay;
private Command cmdExit;
private Command doConnect;
private Form form;
private TextField myHeight;
private TextField myWeight;
private String myBMI;
private ChoiceGroup units;
private String unitText;
private String xunitNumeric;
private String myHeight_val;
private String myWeight_val;
private Alert myAlert;
public BMIcalc() {
myDisplay = Display.getDisplay(this);
form = new Form("Body Mass Index");
units = new ChoiceGroup("Select units", Choice.EXCLUSIVE);
units.append("Metric", null);
units.append("Imperial", null);
myHeight = new TextField("Your height? :", "", 3, TextField.NUMERIC);
myWeight = new TextField("Your weight? :", "", 3, TextField.NUMERIC);
cmdExit = new Command("Exit", Command.EXIT, 1);
doConnect = new Command("Calculate!", Command.OK, 2);
public void startApp() {
public void commandAction(Command c, Displayable s) {
if (c == cmdExit) {
} else if (c == doConnect) {
unitText = new String(units.getString(units.getSelectedIndex()));
if (unitText.compareTo("Metric") == 0) {
xunitNumeric = "0";
} else {
xunitNumeric = "1";
myHeight_val = myHeight.getString();
myWeight_val = myWeight.getString();
try {
connect(xunitNumeric, myHeight_val, myWeight_val);
} catch (Exception e) {
db("connect " + e.toString());
public void itemStateChanged(Item item) {
// no action required here in this application.
private void connect(String xunitNumeric, String myHeight, String myWeight) throws IOException {
InputStream iStrm = null;
ByteArrayOutputStream bStrm = null;
HttpConnection http = null;
String url = "<URL_of_your_web_server> /calculate_bmi.php";
try {
url = url + "?unit=" + xunitNumeric + "&height=" + myHeight + "&weight=" + myWeight;
http = (HttpConnection);
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
int ch = 0;
iStrm = http.openInputStream();
bStrm = new ByteArrayOutputStream();
while ((ch = != -1) {
if (ch != 10 && ch != 13) {
} finally {
if (iStrm != null) {
if (bStrm != null) {
if (http != null) {
myBMI = new String(bStrm.toByteArray());
myAlert = new Alert("Your BMI is", myBMI, null, AlertType.INFO);
myDisplay.setCurrent(myAlert, form);
private void db(String str) {
System.err.print("Msg: " + str);
public void pauseApp() {
public void destroyApp(boolean unconditional) {

PHP script (calculate_bmi.php) server-side

$unit = $_GET["unit"];
$height = $_GET["height"];
$weight = $_GET["weight"];
calculateBMI($unit, $height, $weight);
function calculateBMI($unit, $height, $weight){
if ($unit == "0")
$height = $height / 100;
$bmi = round($weight / ($height * $height), 1);
$height = $height * 100;
} else {
$heightcm = ($height * 2.54) / 100;
$weightkilo = $weight * 0.4536;
$bmi = round($weightkilo / ($heightcm * $heightcm), 1);
echo $bmi;
return $bmi;

Save this PHP script with the name you refer it in the MIDlet, if you wish to change it. You can test the PHP script by formulating the URL and issuing it directly to the web browser.

This script, by execution, will extract the parameters sent by the MIDlet. Then it will call a function with those parameters, the calculation of the BMI index is performed there. As a result the script will echo the BMI calculated, which also will be the result value of this function.

The MIDlet will use an alert to show the resulting value back to the user. Another request can be done after the Alert window has been acknowledged. The MIDlet will let the user to perform calculations until user selects "Exit" soft-button.


  • Remember to replace the <URL_of_your_web_server> with the address of your web server, local or remote.
  • For the PHP script note the path encoded in the example and edit it according to your needs.
  • In all, only minimal checking for errors is included (you could enhance this part according to your needs).

Tested with

  • Nokia N97
  • Nokia X3-02

Development Environment

  • NetBeans IDE 6.8, 7.1
  • S60 3rd Edition FP 1 SDK emulator, Nokia SDK 1.1 for Java
This page was last modified on 25 July 2013, at 11:01.
29 page views in the last 30 days.