📄 httpsample.java
字号:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpSample extends MIDlet implements CommandListener{
private static String defaultURL = "http://localhost:8080/MobileServlet/httpsample";
private Display myDisplay = null;
private Form mainScreen ;
private TextField requestField ;
private Form resultScreen;
private StringItem resultField;
Command sendCommand = new Command("SEND",Command.OK,1);
Command backCommand = new Command("BACK",Command.OK,1);
public HttpSample(){
myDisplay = Display.getDisplay(this);
mainScreen = new Form("Type in a String :");
requestField = new TextField("null","Hello Word !",100,TextField.ANY);
mainScreen.append(requestField);
mainScreen.addCommand(sendCommand);
mainScreen.setCommandListener(this);
}
public void startApp(){
myDisplay.setCurrent(mainScreen);
}
public void pauseApp(){
}
public void destroyApp(boolean b){
}
public void commandAction(Command c,Displayable s){
if(c == sendCommand){
System.out.println("Hello Word !");
String requeststring = requestField.getString();
String resultString = sendPostRequest(requeststring);
resultScreen = new Form("Result String:");
resultField = new StringItem(null,resultString);
resultScreen.append(resultField);
resultScreen.addCommand(backCommand);
resultScreen.setCommandListener(this);
myDisplay.setCurrent(resultScreen);
}else if(c == backCommand ){
requestField.setString("SOMETHING GOOD !");
myDisplay.setCurrent(mainScreen);
}
}
public String sendPostRequest(String requeststring){
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
StringBuffer messagebuffer = new StringBuffer();
try{
hc = (HttpConnection)Connector.open(defaultURL,Connector.READ_WRITE);
System.out.println("hello word !");
hc.setRequestMethod(HttpConnection.POST);
dos = hc.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
for(int i = 0;i<request_body.length;i++){
dos.writeByte(request_body[i]);
}
dos.flush();
dos.close();
dis = new DataInputStream(hc.openInputStream());
int ch;
long len = hc.getLength();
if(len != -1){
for (int i = 0 ;i<len;i++)
if((ch=dis.read())!=-1)
messagebuffer.append((char)ch);
}else{
while((ch=dis.read())!=-1){
messagebuffer.append((char)ch);
}
}
dis.close();
}catch(IOException ioe){
messagebuffer = new StringBuffer("ERROR!");
}finally{
try{
System.out.println("hello word !");
if (hc != null) hc.close();
}catch(IOException ignored){}
//try{
if(dis != null) dis = null;
//}//catch(IOException ignored){}
//try{
if (dos != null){
dos = null;}
// }catch(IOException ignored){}
}
return messagebuffer.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -