?? getdemo.java
字號:
/*
* GetDemo.java
*
* Created on 2005年3月29日, 上午10:18
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
/**
*
* @author Liu Bin
* @version
*/
public class GetDemo extends MIDlet implements CommandListener {
private Display display;
private Form form;
private TextField tfURL;
//定義使用的命令按鈕
private Command cmdExit;
private Command cmdConnect;
public GetDemo() {
try {
jbInit();
} catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
cmdExit = new Command("退出", Command.EXIT, 0);
cmdConnect = new Command("連接", Command.SCREEN, 1);
tfURL = new TextField("Please Input URL",
"http://127.0.0.1:8080",80,TextField.URL);
form = new Form("Httpconnection GET test");
form.append(tfURL);
form.addCommand(cmdExit);
form.addCommand(cmdConnect);
form.setCommandListener(this);
}
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
/**
* 處理命令按鈕事件
*/
public void commandAction(Command cmd, Displayable d) {
if (cmd == cmdExit) {
destroyApp(true);
} else if (cmd == cmdConnect) {
try {
String url = tfURL.getString();
if (!url.startsWith("http://")) {
url = "http://" + url;
}
String ret = requestGet(url);
out(ret);
} catch(Exception e) {
System.out.println("發生異常: " + e.toString());
form.append("發生異常: " + e.toString());
}
}
}
/**
* HttpConnection GET功能
* <p>
* @Param url HTTP地址
*/
public String requestGet(String url) throws IOException{
HttpConnection hpc = null;
DataInputStream dis = null;
String content = "";
try{
// 建立連接
hpc = (HttpConnection)Connector.open(url);
out("創建HttpConnection成功\n");
hpc.setRequestMethod(HttpConnection.GET);
out("setRequestMethod成功\n");
dis = new DataInputStream(hpc.openInputStream());
out("打開InputStream成功\n");
if (hpc.getResponseCode() == HttpConnection.HTTP_OK) {
int character;
// 讀取返回的HTTP內容
out("正在讀取數據...\n");
while((character = dis.read()) != -1){
content +=(char)character;
}
}
} catch(IOException e){
out("讀取數據發生異常:" + e.toString());
} finally{
if(hpc != null){
hpc.close();
hpc = null;
}
if(dis != null){
dis.close();
dis = null;
}
}
content = (unicodeTogb2312(content)).trim();
return content;
}
// ===============================================================
// 由于內容可能有中文,所以在接受到信息后要對內容進行字符集的轉換
// ===============================================================
public static String unicodeTogb2312(String s){
if (s==null){
return "";
}
if (s.equals("")){
return s;
}
try{
return new String(s.getBytes("ISO8859_1"),"gb2312");
} catch(Exception uee){
return s;
}
}
private void out(String msg) {
System.out.print(msg);
form.append(msg);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -