ET和POST。J2ME仍然在它的发展初期,并且无线设备也即将得到大面积的普及。所以,所有有志投身于无线网络编程中的开发者们将得到大展拳脚的好机会。
在无线J2ME设备上实现超文本传输协议(3)
时间:2011-02-28
附录:
/*
* HttpMidlet.java
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpMidlet extends MIDlet implements CommandListener {
//使用默认的URL。用户可以从图形用户接口改变这个值
private static String defaultURL = "http://localhost:8080/test/servlet/EchoServlet";
// 主MIDP 显示
private Display myDisplay = null;
// 输入URL的图形用户接口组件
private Form requestScreen;
private TextField requestField;
// 用于提交请求的图形用户接口组件
private List list;
private String[] menuItems;
// 用于显示服务器响应的图形用户接口组件
private Form resultScreen;
private StringItem resultField;
//用于requestScreen的"send"按钮
Command sendCommand;
// 用于requestScreen的"exit"按钮
Command exitCommand;
// 用于requestScreen的"back"按钮
Command backCommand;
public HttpMidlet(){
// 初始化图形用户接口组件
myDisplay = Display.getDisplay( this );
sendCommand = new Command( "SEND", Command.OK, 1 );
exitCommand = new Command( "EXIT", Command.OK, 1 );
backCommand = new Command( "BACK", Command.OK, 1 );
//显示请求的URL
requestScreen = new Form( "Type in a URL:" );
requestField = new TextField( null, defaultURL, 100, TextField.URL );
requestScreen.append( requestField );
requestScreen.addCommand( sendCommand );
requestScreen.addCommand( exitCommand );
requestScreen.setCommandListener( this );
// 选择想要的HTTP请求方法
menuItems = new String[] {"GET Request", "POST Request"};
list = new List( "Select an HTTP method:", List.IMPLICIT, menuItems, null );
list.setCommandListener( this );
// 先是从服务器上收到的信息
resultScreen = new Form( "Server Response:" );
resultScreen.addCommand( backCommand );
resultScreen.setCommandListener( this );
}//结束HttpMidlet()
public void startApp() {
myDisplay.setCurrent( requestScreen );
}//结束 startApp()
public void commandAction( Command com, Displayable disp ) {
// 当用户点击"send"按钮
if ( com == sendCommand ) {
myDisplay.setCurrent( list );
} else if ( com == backCommand ) {
requestField.setString( defaultURL );
myDisplay.setCurrent( requestScreen );
} else if ( com == exitCommand ) {
destroyApp( true );
notifyDestroyed();
}//结束 if ( com == sendCommand )
if ( disp == list && com == List.SELECT_COMMAND ) {
String result;
if ( list.getSelectedIndex() == 0 ) // 发送一个 GET 请求到服务器
result = sendHttpGet( requestField.getString() );
else // 发送一个 POST 请求到服务器
result = sendHttpPost( requestField.getString() );
resultField = new StringItem( null, result );
resultScreen.append( resultField );
myDisplay.setCurrent( resultScreen );
}//结束if ( dis == list && com == List.SELECT_COMMAND )
}//结束 comman
|