import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class ClientApp extends MIDlet implements CommandListener
{
Display display; TextField tf1,tf2; String tf1Str,tf2Str;
form inputform,returnform;
Command cmdSend,cmdBack;
final static String defaultURL = "http://localhost:8080/examples/servlet/ServletApp";
public ClientApp()
{
display = Display.getDisplay(this);
tf1 = new TextField("input first param:","卢东方",20,TextField.ANY);
tf2 = new TextField("input second param:","王桃群",20,TextField.ANY);
cmdSend = new Command("Send",Command.SCREEN,1);
cmdBack = new Command("Back",Command.SCREEN,1);
inputform = new form("pls input the param:");
inputform.append(tf1); inputform.append(tf2);
inputform.addCommand(cmdSend);
inputform.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(inputform);
}
public void invokeServlet(String url) throws IOException
{
HttpConnection hc = null; DataOutputStream dos = null;
DataInputStream dis = null;
try{
hc = (HttpConnection)Connector.open(url,Connector.READ_WRITE);
//设置请求属性
hc.setRequestMethod(HttpConnection.POST);
//设置为POST请求方式,默认的请求方式是GET
hc.setRequestPRoperty("IF-Modified-Since","15 Oct 2003 08:47:14 GMT");
hc.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
hc.setRequestProperty("Content-Language","en-CA");
hc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
hc.setRequestProperty("Connection","Keep-Alive");
//Connection头可以控制MIDlet和Web服务器之间保持"keep alive"特色。
"keep alive"特色是指在MIDlet和Web服务器间始终使用同一个HTTP连接来多次传递数据
(在通常情况下,HTTP是无连接的协议,每次数据传输完毕后都将断开连接,
而下次传递数据之前将重新建立连接)
//发送请求参数到servlet
dos = hc.openDataOutputStream();
dos.writeUTF(tf1Str); dos.writeUTF(tf2Str);
//用于发送请求参数给servlet
System.out.println("手机传递给servlet的第一个参数为:"+ tf1Str);
//主要起调试的作用,调试的结果将显示在WTK的控制台中
System.out.println("手机传递给servlet的第一个参数为:"+ tf2Str);
dos.flush(); dos.close();
//接收servlet响应数据
ds = new DataInputStream(hc.openInputStream());
String return1Str = dis.readUTF(); String return2Str = dis.readUTF();
System.out.println("手机接收到servlet端传来的第一个参数为:" + return1Str);
//主要起调试的作用,调试的结果将显示在WTK的控制台中
System.out.println("手机接收到servlet端传来的第二个参数为:" + return2Str);
returnform = new form("返回的结果");
returnform.append(return1Str); returnform.append(" ");
//将返回的结果append到resultform中
returnform.append(return2Str); returnform.addCommand(cmdBack);
returnform.setCommandListener(this);
}finally{
if (dis !
新闻热点
疑难解答