📄 httppostexample.java
字号:
/*
* 使用POST方式访问Servlet
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpPostExample extends MIDlet implements CommandListener {
private Display display;
private Form mainForm;
private Command exitCommand;
String account = "newuser";
String password = "123456";
public HttpPostExample() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 1);
mainForm = new Form("服务器的信息");
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
}
public void startApp() {
display.setCurrent(mainForm);
//访问服务器servlet
try {
postServlet();
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void postServlet() throws IOException {
HttpConnection http = null;
InputStream iStrm = null;
OutputStream oStrm = null;
// Data is passed at the end of url for Post
String url = "http://127.0.0.1:8080/TEst/hello";
String rawData = "account=long&password=heihei";
try {
http = (HttpConnection) Connector.open(url);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
http.setRequestProperty("Content-Language", "en-US");
http.setRequestProperty("Content-Length",String.valueOf(rawData.length()));//设置参数长度
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
oStrm =http.openOutputStream();
oStrm.write(rawData.getBytes());
//oStrm.flush();
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("使用Post方式验证通过: \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();
if (oStrm != null)
oStrm.close();
}
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -