Home » Programming

Network connection with J2ME and PHP

By Gibson Tang 31 May 2007 One Comment

Gibson Tang shows you how to have your JavaME applications send and receive data from your web server. From high-score posting to web chats and more. Sample source code included.

Trying to establish a connection to a server using GPRS is a pretty common thing that a lot of J2ME developers would like to do and some do not know how to go about doing this. For this article, I will be going through the mechanics and code required to do such connection. For this, you would need

  • A J2ME midlet
  • A PHP script (PHP version 4.x and above)
  • A web server where you can host your PHP script

Download Source Code

How to establish a connection

There are 2 ways to establish a connection to a server and they are

  • HTTP
  • Socket connection

Using HTTP is the safest bet as HTTP is supported by all mobile phones that support J2ME as HTTP is part of the MIDP 1.0 and MIDP 2.0 specifications. For socket connection, only mobile phones with MIDP 2.0 are able to support it. Therefore, this article will focus on using HTTP to establish a connection to the server.

Do you POST or GET

Once you have established a connection via HTTP, you can send your message using HTTP GET or HTTP POST. For HTTP GET, the URL that you will use communicate to the server would be something like this

http://www.wavefrontsystems.net/server.php?name=1

name refers to the variable name which you will use to send to the server and the value 1 is the variable value. HTTP GET is not recommended since some malicious hacker can just modify the value of name and then do something malicious to your server.

For HTTP POST, the URL that you use to communicate to the server will be just this

http://www.wavefrontsystems.net/server.php

This looks simple eh? The variable is not displayed, but there is no need to panic as the variable is just sent as part of the packet to the server and hence you will not see it here. This also means that some script kiddie is unable to hack your server by modifying your scripts. So for this article, I will use HTTP POST as the method which you will use to send data to the server.

For more details on the difference between HTTP POST and GET and their usage, please go to http://www.cs.tut.fi/~jkorpela/forms/methods.html

Why PHP?

PHP is just the language of choice that I use for this article and you can substitute it for JSP, ASP, ASP.NET etc since the language used does not make a difference. I use PHP as it is pretty easy to learn and use, plus, some web hosts do not have JSP or ASP installed for the users. So far, I’ve seen a few web hosts that do not have JSP or ASP installed, but I have encountered none that do not have PHP installed. So PHP it shall be.

For PHP, you must configure your php.ini file to allow raw HTTP POST data to be received. In order to check if you have raw HTTP POST data configured as on, just create a phpinfo.php file with the following lines of code and then access this phpinfo.php file with your web browser.

To configure your php.ini file, just look for always_populate_raw_post_data and make sure that it is set to On

Look under PHP Core configuration for this line always_populate_raw_post_data and if it is On, then you are set to go

But first, let us look at the client

Download the zip file and open GameScreen.java. Next, look for the function sendToServer() which has all the code that will enable you to send a message to the PHP file hosted on the server and then retrieve a response. Let us go through the code and step through the important functions, shall we?

public void sendToServer()
    {
        //declare the http connection
        HttpConnection      hcon = null;

        //open the input stream to receive data from the server
        DataInputStream     dis = null;

        //open the output stream to send data to the server
        DataOutputStream    dos = null;

        //holds the result of the connection, whether pass or fail
        httpResult = 0;

        //the message string that you will send to the server
        String str = msgField.getString();

        //this is to be the response message from the server
        StringBuffer responseMessage = new StringBuffer();

        try {
                //open a connection to the specific URL
            hcon = ( HttpConnection )Connector.open
                        ("http://www.wavefrontsystems.net/server.php");
                // set the request method to POST
            hcon.setRequestMethod( HttpConnection.POST );

            print("request method set");
                //set the content length of the message that you want to send
            hcon.setRequestProperty("Content-Length", Integer.toString(str.length()));
                // obtain DataOutputStream for sending the request string
            dos = hcon.openDataOutputStream();
            print("open output stream");

            print("length:" + str.length());

                // send request string to server

                //send the message through the dataoutputstream
            dos.write(str.getBytes());
            print("sending to server the string:" + str);

                //open the datainputstream to receive the server response
            dis = new DataInputStream(hcon.openInputStream());
                //get the response code
            switch(hcon.getResponseCode())
            {
                case HttpConnection.HTTP_OK:
                case HttpConnection.HTTP_CREATED: //if positive response
                    httpResult = 1;
                    int ch;
                    while( (ch = dis.read() ) != -1 ) {
                        //get server message and add to the responseMessage variable
                        responseMessage.append( (char)ch );
                    }
                    print("ok");

                    break;
                default: //if negative response
                    httpResult = -1;
                    print("not ok");
            }

            response = responseMessage.toString();
            display.setCurrent(this);
            gameState = 44;
        }
        catch( Exception e )
        {
            e.printStackTrace();
            httpResult = -2;
            responseMessage.append( "ERROR" );
        }
        finally
        {
            // free up i/o streams and http connection
            try
            {
                if( hcon != null ) hcon.close(); //close connection if open
                if( dis != null ) dis.close(); //close datainputstream if open
                if( dos != null ) dos.close(); //close dataoutputstream if open
            }
            catch ( IOException ioe )
            {
                ioe.printStackTrace();
            } //end try/catch
        } //end try/catch/finally

    print(responseMessage.toString());
    }

First, we open the HTTP connection by declaring

HttpConnection      hcon = null;

Then we open the dataoutputstream and the datainputstream by declaring

DataInputStream     dis = null;

And

DataOutputStream    dos = null;

respectively. The dataoutputstream must be declared if you want to send a message to the server and the datainputstream is declared so that you can receive a response message from the server.

hcon = ( HttpConnection )Connector.open
    ("http://www.gibsontang.com/server.php");

is used to tell the connector to connect to the specific server script which in this case is http://www.gibsontang.com/server.php

hcon.setRequestMethod( HttpConnection.POST );

will then set the connection method to HTTP POST. Alternatively, you can use HttpConnection.GET if you are using HTTP GET. But for this article, we will be using HttpConnection.GET.

hcon.setRequestProperty("Content-Length", Integer.toString(str.length()));

will then tell the server how many bytes of data to expect for this sending session.

dos = hcon.openDataOutputStream();

will open the dataoutputstream so that you can prepare to send the data over to the server.

dos.write(str.getBytes());

is the line that sends the data over to the server via the dataoutputstream.

Now that the data has been sent, we can now expect a response from the server, so let us look at how we should handle that.

dis = new DataInputStream(hcon.openInputStream());

will open the datainputstream in preparation to receive a response.

    switch(hcon.getResponseCode())//get the response code
    {
        case HttpConnection.HTTP_OK:
        case HttpConnection.HTTP_CREATED://if there is a positive response
            httpResult = 1;
            int ch;
            while( ( ch = dis.read() ) != -1 ) {
                //get server message and add to the responseMessage variable
                responseMessage.append( (char)ch );
            }
            print("ok");

            break;

        default://if there is a negative response
            httpResult = -1;
            print("not ok");
    }

hcon.getResponseCode() will retrieve the response code from the server. If the response code is HttpConnection.HTTP_OK or HttpConnection.HTTP_ CREATED, then that means the connection was valid and we can expect a non erroneous response from the server.

    while( ( ch = dis.read() ) != -1 )
        responseMessage.append( (char)ch );

So while the dis.read() does not return a -1 which signals the end of the return message, we would add the character to the stringbuffer responseMessage which will hold the response message that we get from the server.

    finally
    {
        // free up i/o streams and http connection
        try
        {
            //close the connection if it is open
            if ( hcon != null ) hcon.close();
            //close the datainputstream if it is open
            if (dis != null ) dis.close();
            //close the dataoutputstream if it is open
            if (dos != null ) dos.close();
        }
        catch ( IOException ioe )
        {
            ioe.printStackTrace();
        }//end try/catch
    }//end try/catch/finally

Finally, we need to close up the http connector hcon, dataoutputstream dos and datainputstream dis so that it is not left dangling in the case of any unforeseen error. This will also prevent many weird bugs from occurring in the future.

Now that we have gone through the midlet code, let us look at the server code.

And now, on to the server

The server code for server.php looks like this

This line file_get_contents(’php://input’) will retrieve the data that your midlet sent via the dataoutputstream. Next, you will need to send a response back to your midlet and this line will do it.

$response = "The message is " . $str;

The above line will also output text to your web browser if you access it the server.php file via your browser.

Finally, to wrap it all up

This is how a J2ME midlet connects to a server, sends data to the server and how the midlet will receive a response from the server. To sum it up, you just have to

  1. Set the connector to connect to the URL:
  2. Set the request method to HTTP POST or HTTP GET
  3. Set the content-length to let the server know how much data to expect
  4. Open the dataoutputstream in order to send the data over
  5. Send the data over
  6. Open the datainputstream to receive the server response
  7. Read in the server response

It is actually pretty simple once you get the hang of it and once you do, you can do a lot of stuff with this such as sending high scores to a server etc. So this is Gibson Tang, signing off.

One Comment »

  • emi said:

    Hi, the server´s code is not show on the page, could you add it.

    Thanks.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.