日期:2014-05-20  浏览次数:20933 次

关于J2ME网络连结的问题,谢谢各位的帮忙!
客户端是这样的
package com_test;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.*;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class HttpGetExample extends MIDlet implements CommandListener{
private Display display;
private Form MainForm;
private Command cmdExit,cmdcomfirm;
String account="newuser";
String pwd="123456";
public HttpGetExample() {
display=Display.getDisplay(this);
cmdExit=new Command("Exit",Command.EXIT,1);
cmdcomfirm=new Command("comfirm",Command.OK,1);
MainForm=new Form("data from servlet");
MainForm.addCommand(cmdcomfirm);
MainForm.addCommand(cmdExit);
MainForm.setCommandListener(this);
}
public void callServlet() throws IOException
{
HttpConnection conn=null;
InputStream is=null;
String url="http://127.0.0.1:9001/servlet/hello"+"?"+"account="+account+"&"+"pwd="+pwd;
try
{
conn=(HttpConnection)Connector.open(url);
conn.setRequestMethod(HttpConnection.GET);
if(conn.getResponseCode()==conn.HTTP_OK)
{
is=conn.openInputStream();
int len=(int)conn.getLength();
if(len>0)
{
byte servletdata[] =new byte[len];
is.read(servletdata);
MainForm.append("验证通过\n"+new String(servletdata));
}else
{
MainForm.append("不能访问数据!");
}
}



}catch(Exception e)
{
MainForm.append("网络出错");
System.out.println(e.getMessage());
}
finally
{
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null)
{
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub

}

protected void pauseApp() {
// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException {
display.setCurrent(MainForm);

}

public void commandAction(Command c, Displayable d) {

if(c==cmdcomfirm)
{
Thread t=new Thread()
{
public void run()
{
try {
callServlet();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
else if(c==cmdExit)
{
try {
this.destroyApp(false);
} catch (MIDletStateChangeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
notifyDestroyed();
}
}

}


这是服务器端的

package com_test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

/**
* Constructor of the object.
*/
public HelloWorld() {