📄 httpgetdata.java
字号:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpGetData extends MIDlet implements CommandListener {
private Form form;
private TextField tfURL;
private Display display;
private Command cmdExit;
private Command cmdConnect;
private void myInit() {
cmdExit = new Command("Exit", Command.EXIT, 0);
cmdConnect = new Command("Conn", Command.SCREEN, 1);
tfURL = new TextField("Please Input URL",
"http://www.google.com", 80, TextField.URL);
form = new Form("Httpconnection GET test");
form.append(tfURL);
form.addCommand(cmdExit);
form.addCommand(cmdConnect);
form.setCommandListener(this);
}
public HttpGetData() {
display = Display.getDisplay(this);
myInit();
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(form);
}
private void out(String msg) {
// System.out.print(msg);
form.append(msg);
}
private String requestGet(String url) {
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;
out("正在读取数据...\n");
while ((character = dis.read()) != -1) {
content += (char) character;
}
}
} catch (IOException err) {
out("读取数据发生异常:" + err.toString());
} finally {
if (hpc != null) {
try {
hpc.close();
} catch (Exception e) {
}
hpc = null;
}
if (dis != null) {
try {
dis.close();
} catch (Exception e) {
}
dis = null;
}
}
content = (unicodeTogb2312(content)).trim();
return content;
}
private String unicodeTogb2312(String s) {
if (s == null) {
return "";
}
if (s.equals("")) {
return s;
}
try {
return new String(s.getBytes("ISO8859_1"), "gb2312");
} catch (Exception err) {
return s;
}
}
public void commandAction(Command c, Displayable s) {
if (c == cmdExit) {
try {
destroyApp(true);
} catch (Exception err) {
}
} else if (c == cmdConnect) {
try {
String url = tfURL.getString();
if (!url.startsWith("http://"))
url = "http://" + url;
String ret = requestGet(url);
out(ret);
} catch (Exception err) {
form.append("发生异常:" + err.toString());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -