关于J2ME与Servlet通信中的一些问题,在线跪求答案
现在正在做J2ME与Servlet之间通信的程序,但是在发送的时候总是有异常。下面是我的代码,希望各位高手指导指导。
public class httpGet extends MIDlet implements CommandListener {
public void commandAction(Command cmd, Displayable dis) {
if(cmd == downloadCommand) {
http.setName(nameF.getString());
http.setPass(passF.getString());
synchronized(this){
notify();
}
}
}
package src;
import java.io.*;
import javax.microedition.io.*;
public class HttpThread implements Runnable{
//private String url = " ";
private httpGet midlet = null;
private boolean done = false;
public static final String HOST = "http://192.168.44.88:8080/do/servlet/Select? ";
public static final String HOST1 = "http://localhost:8080/server/servlet/server ";
public static final String HOST3 = "http://192.168.44.88:8080 ";
public String name = null;
public String PassWrod = null;
public HttpThread(httpGet midlet) {
this.midlet = midlet;
}
//public void setURL (String url) {
//this.url = url;
//}
public HttpConnection openConnection() throws IOException {
HttpConnection conn = (HttpConnection)Connector.open(HOST1,Connector.READ_WRITE);
return conn;
}
public void setName(String name){
this.name = name;
}
public void setPass(String pass){
this.PassWrod = pass;
}
public void run() {
while(!done) {
synchronized (midlet) {
try{
try {
midlet.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!done) {
HttpConnection conn = openConnection();
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty( "IF-Modified-Since ", "15 Oct 2003 08:47:14 GMT ");
conn.setRequestProperty( "User-Agent ", "Profile/MIDP-2.0 Configuration/CLDC-1.1 ");
conn.setRequestProperty( "Content-Language ", "en-CA ");
conn.setRequestProperty( "Content-Type ", "application/x-www-form-urlencoded ");
conn.setRequestProperty( "Connection ", "Keep-Alive ");
int responseCode = conn.getResponseCode();
if(responseCode != HttpConnection.HTTP_OK){
midlet.error();
}
DataOutputStream dos = conn.openDataOutputStream();
dos.writeUTF(name);
dos.writeUTF(PassWrod);
dos.flush();
System.out.println( "send massage is: " + name);
DataInputStream dis = conn.openDataInputStream();
int result = dis.readInt();
System.out.println( "resave massage is: " + result);
midlet.displayResult(result);
dis.close();
dos.close();
conn.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
运行的时候提示
java.lang.IllegalStateException: Write attempted after request finished
[解决办法]
java.lang.IllegalStateException: Write attempted after request finished
对于http连接,仅能进行一次读写,并且要先写入完毕才能打开输入流进行读操作
[解决办法]
还有,在客户端POST的时候设置一下Content-Length:
conn.setRequestProperty( "Content-Length ", "数据长度 ");