📄 httpgetexample.java
字号:
/*
* 使用Get方式访问Servlet
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpGetExample extends MIDlet implements CommandListener {
private Display display;
private Form mainForm;
private Command exitCommand;
String account = "newuser";
String password = "123456";
public HttpGetExample() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 1);
mainForm = new Form("Data from servlet");
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
}
public void startApp() {
display.setCurrent(mainForm);
//访问服务器servlet
try {
callServlet();
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private void callServlet() throws IOException {
HttpConnection http = null;
InputStream iStrm = null;
// Data is passed at the end of url for GET
String url = "http://127.0.0.1:8080/TEst/hello" + "?" + "account="
+ account + "&" + "password=" + password;
try {
http = (HttpConnection) Connector.open(url);
//使用HttpConnection.GET方式
// 发送Get请求
http.setRequestMethod(HttpConnection.GET);
// 服务器响应
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
iStrm = http.openInputStream();
// 获得头信息,没有返回
//获得数据信息
int length = (int) http.getLength();
if (length > 0) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
//显示返回信息
mainForm.append("验证通过: \n"
+ new String(servletData));
} else
mainForm.append("不能访问数据!");
}
} catch (Exception e) {
mainForm.append("网络出错");
System.out.println(e.toString());
} finally {
//关闭连接对象
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -