Monday, January 23, 2012

Using GET and POST methods in J2ME

Most of the mobile applications are not alone. They frequently communicate with web services or web applications to accomplish their tasks. Lets see how to make GET and POST requests to a server.
We can use HttpConnection class to make requests.
Lets see what are the basic steps.
Java(midp) Code :
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 *
 * @author Kanishka
 * References :
 * http://www.java2s.com/Code/Java/J2ME/SampletodemonstrateHttpGETandPOSTfromMIDlet.htm
 * http://codetrips.blogspot.com/2007/04/http-post-from-j2me-midlet.html
 */
public class HttpCommunication {
    public String doPostRequest(String city,String code){
        StringBuffer result=new StringBuffer("");
        HttpConnection httpCon=null;
        //String url="http://kdkanishka.alwaysdata.net/midp/midpreq.php";
        String url="http://localhost/midp/midpreq.php";
        InputStream ins=null;
        OutputStream ous=null;
        try{
            //create http connection object to make requests
            httpCon=(HttpConnection) Connector.open(url,Connector.READ_WRITE);
            httpCon.setRequestMethod(HttpConnection.POST);
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestProperty("User-Agent", "HttpMidlet/0.2");
            httpCon.setRequestProperty("My-Custom-Property", "Requets from Kanishka");

            //defining POST data
            String postdata="city="+city+"&code="+code;
            System.out.println(postdata);

            //set content length
            //important : Without a content length a JSP will not process POST data
            httpCon.setRequestProperty("Content-length",String.valueOf(postdata.getBytes().length));
            //after this step any call to setResuestProperty method will raise IOException

            //now we have to write data to the server
            ous=httpCon.openOutputStream();
            ous.write(postdata.getBytes());
            ous.flush();
            ous.close();

            int response_code=httpCon.getResponseCode();
            if(response_code==HttpConnection.HTTP_OK){ //if server has a response
                int responseLen=(int) httpCon.getLength();
                System.out.println(responseLen);
                ins=httpCon.openInputStream();
                if(ins==null){
                    result.append("Cannot open server response!");
                }
                
//                if(responseLen>0){
//                    int chr;
//                    while((chr=ins.read())!=-1){
//                        result.append((char)chr);
//                    }
//                }
                byte[] respData=new byte[responseLen];
                ins.read(respData);
                String tmp=new String(respData);
                result.append(tmp);

            }
        }catch(IOException e){
            result.append("Network Problem : " + e.getMessage());
        }finally{
            if(ins!=null){
                try {
                    ins.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if(ous!=null){
                try {
                    ous.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("Connection closed!");
        }

        return result.toString();
    }
}
PHP Code :
<?php
//data manipulation part
$areacodes=array();
$areacodes['63']="Ampara";
$areacodes['25']="Anuradhapura";
$areacodes['55']="Badulla";
$areacodes['65']="Batticaloa";
$areacodes['91']="Galle";
$areacodes['33']="Gampaha";
$areacodes['21']="Jaffna";
$areacodes['67']="Kalmunai";
$areacodes['81']="Kandy";
$areacodes['11']="Kelaniya";
$areacodes['37']="Kurunegalla";
$areacodes['11']="Maharagama";
$areacodes['23']="Mannar";
$areacodes['41']="Matara";
$areacodes['11']="Moratuwa";
$areacodes['11']="Colombo";
$areacodes['31']="Negombo";
$areacodes['52']="Nuwara Eliya";
$areacodes['27']="Polonnaruwa";
$areacodes['32']="Puttalama";
$areacodes['55']="Rantembe";
$areacodes['45']="Ratnapura";
$areacodes['26']="Trincomalee";
$areacodes['24']="Vavuniya";

//communication part
$code=$_POST['code'];
$city=$_POST['city'];
if(strlen($code)>0){
 //user provided code
 $city=findArea($areacodes,$code);
 echo $city;
}else if(strlen($city)>0){
 //user provided city
 $code=findCode($areacodes,$city);
 echo $code;
}

function findArea($array,$code){
 foreach ($array as $id=>$value){
  if(strcmp($code,$id)==0){
   return $value;
  }
 }
}

function findCode($array,$area){
 foreach($array as $id=>$value){
  if(strcmp($area,$value)==0){
   return $id;
  }
 }
}
?>
GUI (Coded based on LWUIT)
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import javax.microedition.midlet.*;

/**
 * @author Kanishka
 */
public class AreaCodes extends MIDlet implements ActionListener{
    TextField txtCity=null;
    TextField txtCode=null;
    TextField txtResult=null;
    Button btnSubmit=null;
    Command cmdExit=null;

    public void startApp() {
        Display.init(this);
        Form f=new Form("Area Codes Demo");
        txtCity=new TextField();
        txtCode=new TextField();
        txtResult=new TextField();
        btnSubmit=new Button("Submit!");

        f.addComponent(new Label("Area Code :"));
        f.addComponent(txtCode);
        f.addComponent(new Label("City :"));
        f.addComponent(txtCity);
        f.addComponent(txtResult);
        f.addComponent(btnSubmit);

        cmdExit=new Command("Exit!");
        f.addCommand(cmdExit);
        f.setCommandListener(this);
        btnSubmit.addActionListener(this);

        f.show();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getCommand()==cmdExit){
            destroyApp(false);
            notifyDestroyed();
        }else if(arg0.getSource()==btnSubmit){
            String res=new HttpCommunication().doPostRequest(txtCity.getText(), txtCode.getText());
            txtResult.setText(res);
        }
    }
}

1 comments:

  1. Hi there, awesome site. I thought the topics you posted on were very interesting. I tried to add your RSS to my feed reader and it a few. take a look at it,

    hopefully I can add you and follow.

    J2ME Application Development

    ReplyDelete

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis