📄 httplogger.java
字号:
package HttpThread;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
public class HttpLogger extends MIDlet {
private Display display;
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command okCommand = new Command("OK", Command.OK, 1);
private Command cancelCommand = new Command("Cancel", Command.CANCEL, 1);
private URLEntry mainForm;
public HttpLogger() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
exitMIDlet();
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initMIDlet();
}
}
private void initMIDlet() {
display = Display.getDisplay(this);
mainForm = new URLEntry();
display.setCurrent(mainForm);
}
public void exitMIDlet() {
notifyDestroyed();
}
// 显示错误信息
void displayError(Throwable e, Displayable next) {
Alert a = new Alert("Exception");
a.setString(e.toString());
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, next);
}
// 输入URL
class URLEntry extends TextBox implements CommandListener {
URLEntry() {
super("Enter URL:", "http://127.0.0.1:8080/HelloWorld.html", 100, 0);
addCommand(exitCommand);
addCommand(okCommand);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
exitMIDlet();
} else if (c == okCommand) {
Logger f = new Logger(this, getString());
Thread t = new Thread(f);
t.start();
display.setCurrent(f);
}
}
}
// 连接网络的新线程
class Logger extends Form implements Runnable, CommandListener {
private Displayable next;
private HttpConnection conn;
private String url;
private StringItem text = new StringItem(null, "");
Logger(Displayable next, String url) {
super("HTTP 信息");
this.url = url;
this.next = next;
addCommand(cancelCommand);
setCommandListener(this);
append(text);
}
public void commandAction(Command c, Displayable d) {
display.setCurrent(next);
try {
conn.close();
} catch (IOException e) {
displayError(e, next);
}
}
public void run() {
//创建一个连接不要放在构造函数中
try {
conn = (HttpConnection) Connector.open(url);
} catch (IOException e) {
e.printStackTrace();
}
update("连接到" + conn.getURL());
try {
int rc = conn.getResponseCode();
update("Response code: " + rc);
update("Response message: " + conn.getResponseMessage());
String key;
for (int i = 0; (key = conn.getHeaderFieldKey(i)) != null; ++i) {
update(key + ": " + conn.getHeaderField(i));
}
} catch (IOException e) {
update("获得的异常: " + e.toString());
}
removeCommand(cancelCommand);
addCommand(okCommand);
}
// 使用string item显示获得的信息
void update(String line) {
if (display.getCurrent() != this)
return;
String old = text.getText();
StringBuffer buf = new StringBuffer();
buf.append(old);
if (old.length() > 0) {
buf.append('\n');
}
buf.append(line);
text.setText(buf.toString());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -