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

WAP之家技术文章J2ME技术程序开发使用POST和GET方法与servlet通信

使用POST和GET方法与servlet通信
作者:java2s  来源:java2s  发布时间:2006-7-25 8:58:07
/*--------------------------------------------------
* GetNpost.java

*
* Use GET or POST to communicate with a Java servlet. 
* The servlet will search a database for the balance
* of an account.
*
* 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.io.*;
import java.io.*;

public class GetNpost extends MIDlet implements CommandListener
{
  private Display display;      // Reference to Display object
  private Form fmMain;         // The main form
  private Alert alError;       // Alert to error message
  private Command cmGET;       // Request method GET
  private Command cmPOST;      // Request method Post  
  private Command cmExit;      // Command to exit the MIDlet
  private TextField tfAcct;    // Get account number
  private TextField tfPwd;     // Get password
  private StringItem siBalance;// Show account balance
  private String errorMsg = null;
  public GetNpost()
  {
    display = Display.getDisplay(this);

    // Create commands
    cmGET = new Command("GET", Command.SCREEN, 2);
    cmPOST = new Command("POST", Command.SCREEN, 3);    
    cmExit = new Command("Exit", Command.EXIT, 1);

    // Textfields
    tfAcct = new TextField("Account:"""5, TextField.NUMERIC);
    tfPwd = new TextField("Password:"""10, TextField.ANY | TextField.PASSWORD);        

    // Balance string item
    siBalance = new StringItem("Balance: $""");

    // Create Form, add commands & componenets, listen for events
    fmMain = new Form("Account Information");    
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmGET);
    fmMain.addCommand(cmPOST);
    fmMain.append(tfAcct);
    fmMain.append(tfPwd);
    fmMain.append(siBalance);
    fmMain.setCommandListener(this);   
  }

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

  public void pauseApp()
  { }
  public void destroyApp(boolean unconditional)
  { }

  public void commandAction(Command c, Displayable s)
  {
    if (c == cmGET || c == cmPOST)
    {
      try 
      {
        if (c == cmGET)
          lookupBalance_withGET()
        else
          lookupBalance_withPOST();
      }
      catch (Exception e)
      
        System.err.println("Msg: " + e.toString());
      }
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    
  }

  /*--------------------------------------------------
  * Access servlet using GET
  *-------------------------------------------------*/    
  private void lookupBalance_withGET() throws IOException
  {
    HttpConnection http = null;
    InputStream iStrm = null;    
    boolean ret = false;

    // Data is passed at the end of url for GET
    String url = "http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet" "?" +
                 "account=" + tfAcct.getString() "&" 
                 "password=" + tfPwd.getString();
    try
    {
      http = (HttpConnectionConnector.open(url);
      //----------------
      // Client Request
      //----------------
      // 1) Send request method
      http.setRequestMethod(HttpConnection.GET);
      // 2) Send header information - none
      // 3) Send body/data -  data is at the end of URL

      //----------------
      // Server Response
      //----------------
      iStrm = http.openInputStream();      
      // Three steps are processed in this method call
      ret = processServerResponse(http, iStrm);
    }
    finally
    {
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (http != null)
        http.close();
    }

    // Process request failed, show alert    
    if (ret == false)
      showAlert(errorMsg);        
  }

  /*--------------------------------------------------
  * Access servlet using POST
  *-------------------------------------------------*/  
  private void lookupBalance_withPOST() throws IOException
  {
    HttpConnection http = null;
    OutputStream oStrm = null;
    InputStream iStrm = null;    
    boolean ret = false;
    // Data is passed as a separate stream for POST (below)
    String url = "http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet";
    try
    {
      http = (HttpConnectionConnector.open(url);
      oStrm = http.openOutputStream();
      //----------------
      // Client Request
      //----------------
      // 1) Send request type
      http.setRequestMethod(HttpConnection.POST)
      // 2) Send header information. Required for POST to work!
      http.setRequestProperty("Content-Type""application/x-www-form-urlencoded");

      // If you experience connection/IO problems, try 
      // removing the comment from the following line
      //   http.setRequestProperty("Connection", "close");      

      // 3) Send data/body
      // Write account number
      byte data[] ("account=" + tfAcct.getString()).getBytes();
      oStrm.write(data);
      // Write password
      data = ("&password=" + tfPwd.getString()).getBytes();
      oStrm.write(data);
      // For 1.0.3 remove flush command
      // See the note at the bottom of this file
//      oStrm.flush();

      //----------------
      // Server Response
      //----------------
      iStrm = http.openInputStream();      
      // Three steps are processed in this method call      
      ret = processServerResponse(http, iStrm);
    }
    finally
    {
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (oStrm != null)
        oStrm.close();        
      if (http != null)
        http.close();
    }

    // Process request failed, show alert    
    if (ret == false)
      showAlert(errorMsg);        
 }

  /*--------------------------------------------------
  * Process a response from a server
  *-------------------------------------------------*/
  private boolean processServerResponse(HttpConnection http, InputStream iStrmthrows IOException
  {
    //Reset error message
    errorMsg = null;
    // 1) Get status Line
    if (http.getResponseCode() == HttpConnection.HTTP_OK)
    {
      // 2) Get header information - none
      // 3) Get body (data)
      int length = (inthttp.getLength();
      String str;
      if (length != -1)
      {
        byte servletData[] new byte[length];
        iStrm.read(servletData);
        str = new String(servletData);
      }
      else  // Le

[1] [2]  下一页

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

用户名: 查看更多评论

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

内 容:

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