WAP之家:为您提供最全最新的WAP技术,CP.SP.3G等行业资讯。 WAP之家交流论坛全新开放 点击进入>>
WAP资讯 | 3G动态 | SP动态 | 运营商动态 | 内容商动态 | 制造商动态 | 论坛讨论>> 每次自动访问
WAP技术 | WAP源码 | 手机编程 | 手机源码 | 无线技术 | J2ME技术 | 手机软件 添加到收藏夹
IVR技术 | SP资料 | SMS MMS技术 | 商业方案 | IVR下载 | 书籍教程 | 工具软件 语言:繁體中文

WAP之家技术文章J2ME技术程序开发MIDlet与Servlet之间传递Cookie

MIDlet与Servlet之间传递Cookie
作者:java2s  来源:java2s  发布时间:2006-7-25 8:59:29

*--------------------------------------------------
* Cookie.java
*
* Pass a cookie (stored in rms) between the MIDlet
* and a Java servlet. The cookie is generated  
* by the servlet on the first visit.
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;
public class Cookie extends MIDlet implements CommandListener
{
  private Display display;
  private TextBox tbMain;
  private Form fmMain;
  private Command cmExit;
  private Command cmLogon;
  private String cookie = null;
  private RecordStore rs = null;  
  static final String REC_STORE = "rms_cookie";  
  private String url = "http://www.mycgiserver.com/servlet/corej2me.CookieServlet";

  public Cookie()
  {
    display = Display.getDisplay(this);

    // Create commands
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmLogon = new Command("Logon", Command.SCREEN, 2);    
    // Create the form, add commands, listen for events
    fmMain = new Form("");
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmLogon);
    fmMain.setCommandListener(this);

    // Read cookie if available
    openRecStore();   
    readCookie();
      // System.out.println("Client cookie: " + cookie);        
  }

  public void startApp()
  {
    display.setCurrent(fmMain);
  }    

  public void pauseApp()
  { }

  public void destroyApp(boolean unconditional)
  
    closeRecStore();  // Close record store
  }

  public void openRecStore()
  {
    try
    {
      // The second parameter indicates that the record store
      // should be created if it does not exist
      rs = RecordStore.openRecordStore(REC_STORE, true);
    }
    catch (Exception e)
    {
      db("open " + e.toString());
    }
  }    
  public void closeRecStore()
  {
    try
    {
      rs.closeRecordStore();
    }
    catch (Exception e)
    {
      db("close " + e.toString());
    }
  }

  /*--------------------------------------------------
  * Write cookie to rms
  *-------------------------------------------------*/
  public void writeRecord(String str)
  {
    byte[] rec = str.getBytes();

    try
    {
      rs.addRecord(rec, 0, rec.length);
    }
    catch (Exception e)
    {
      db("write " + e.toString());
    }
  }

  /*--------------------------------------------------
  * Read cookie from rms
  *-------------------------------------------------*/
  public void readCookie()
  {
    try
    {
      byte[] recData = new byte[25]
      int len;

      if (rs.getNumRecords() 0)
      {
        // Only one record will ever be written, safe to use '1'      
        if (rs.getRecordSize(1> recData.length)
          recData = new byte[rs.getRecordSize(1)];
        len = rs.getRecord(1, recData, 0);

        cookie = new String(recData);
      }
    }
    catch (Exception e)  {
      db("read " + e.toString());
    }
  }

  /*--------------------------------------------------
  * Send client request and recieve server response
  *
  * Client: If cookie exists, send it to the server
  *
  * Server: If cookie is sent back, this is the 
  *         clients first request to the server. In
  *         that case, save the cookie. If no cookie
  *         sent, display server body (which indicates
  *         the last time the MIDlet contacted server).
  *-------------------------------------------------*/    
  private void connect() throws IOException
  {
    InputStream iStrm = null;
    ByteArrayOutputStream bStrm = null;
    HttpConnection http = null;    
    try
    {
      // Create the connection
      http = (HttpConnectionConnector.open(url);

      //----------------
      // Client Request
      //----------------
      // 1) Send request method
      http.setRequestMethod(HttpConnection.GET);
      // If you experience connection/IO problems, try 
      // removing the comment from the following line
      //http.setRequestProperty("Connection", "close");      

      // 2) Send header information
      if (cookie != null)
        http.setRequestProperty("cookie", cookie);
      System.out.println("Client cookie: " + cookie);      

      // 3) Send body/data - No data for this request
      //----------------
      // Server Response
      //----------------
      // 1) Get status Line
      if (http.getResponseCode() == HttpConnection.HTTP_OK)
      {
        // 2) Get header information         
        String tmpCookie = http.getHeaderField("set-cookie");        
           System.out.println("server cookie: " + tmpCookie);
        // Cookie will only be sent back from server only if 
        // client (us) did not send a cookie in the first place.
        // If a cookie is returned, we need to save it to rms
        if (tmpCookie != null)
        {
          writeRecord(tmpCookie);
          // Update the MIDlet cookie variable
          cookie = tmpCookie;
          fmMain.append("First visit\n");          
          fmMain.append("Client : " + cookie + "\n");
        }        
        else  // No cookie sent from server
        {
          // 3) Get data, which is the last time of access
          iStrm = http.openInputStream();
          int length = (inthttp.getLength();
          String str;
          if (length != -1)
          {
            byte serverData[] new byte[length];
            iStrm.read(serverData);
            str = new String(serverData);
          }
          else  // Length not available...
          {
            bStrm = new ByteArrayOutputStream();       
            int ch;
            while ((ch = iStrm.read()) != -1)
              bStrm.write(ch);

            str = new String(bStrm.toByteArray());
          }
          // Append data to the form           
          fmMain.append("Last access:\n" + str + "\n");                   
        }
      }
    }
    finally
    {
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (bStrm != null)
        bStrm.close();                
      if (http != null)
        http.close();
    }
  }
  /*--------------------------------------------------
  * Process events
  *-------------------------------------------------*/
  public void commandAction(Command c, Displayable s)
  {
    // If the Command button pressed was "Exit"
    if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (c == cmLogon)
    {
      try 
      {
        // Logon to the servlet
        connect();     
      }
      catch (Exception e)
      {

[1] [2]  下一页

[] [返回上一页] [打 印]
文章评论

用户名: 查看更多评论

分 值:100分 85分 70分 55分 40分 25分 10分 0分

内 容:

         (注“”为必填内容。) 验证码: 验证码,看不清楚?请点击刷新验证码