刚试过这个,但它失败了。我使用蓝牙将我的midlet上传到手机,并尝试连接到我在PC上运行的servlet但它失败了。我的想象是使用调制解调器将我的电脑连接到互联网,然后获取其IP地址并用该IP地址替换midlet中的url中的localhost并构建它并将其放入手机中。那没起效。可以做些什么?请帮忙
这是我的代码:Midlet:`import javax.microedition.midlet。; // midlet类包导入 导入javax.microedition.lcdui。; //用于ui和命令的包 import javax.microedition.io。; // import java.io。;
/ ** * @author k'owino * / //定义midlet类 public class mmm extends MIDlet实现了CommandListener {
private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;//welcome form
private Form welForm2;//welcome form
private Form welForm3;//welcome form
private List mainMenu;//vote code
private List voteCats;//vote cats
private List voteCats2;//vote cats
private StringItem welStr;
private StringItem welStr1;
private TextField codeField;
private StringItem codeError;
private Command quitCmd;
private Command contCmd;
private Command quitCmd1;
private Command contCmd1;
private Command quitCmd3;
private Command contCmd3;
private Command okCmd;
private Command quCmd;
private Command bkCmd;
private Command ok2Cmd;
String codefield;
public static String[] list_wrd = new String[100];
public static String[] list_wrd1 = new String[100];
public static String track = "";
int l;
int g;
String selected, postn_scted;
String cnfrm, cnfrm2;
String st2;
//constructor of the midlet
public mmm() {
display = Display.getDisplay(this);//creating the display object
welForm = new Form("THE MVS");//instantiating welForm object
welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
+ "Please enter your voting code below");//instantiating welStr string item
codeError = new StringItem("", "");//intantiating phone error string item
codeField = new TextField("Voting code", "", 10, TextField.PASSWORD);//phone number field object
quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
welForm.append(welStr);//adding welcome string item to form
welForm.append(codeField);//adding phone field to form
welForm.append(codeError);//adding phone error string item to form
welForm.addCommand(contCmd);//adding continue command
welForm.addCommand(quitCmd);//adding quit command
welForm.setCommandListener(this);
display.setCurrent(welForm);
}
//start application method definition
public void startApp() {
}
//pause application method definition
public void pauseApp() {
}
//destroy application method definition
public void destroyApp(boolean unconditional) {
}
//Command action method definition
public void commandAction(Command c, Displayable d) {
if (d == welForm) {
if (c == quitCmd) {
exitMidlet();//call to exit midlet
} else {//if the command is contCmd
//place a waiting activity indicator
System.out.println("ken de man");
Thread t = new Thread() {
public void run() {
try {
//method to connect to server
sendPhone();
} catch (Exception e) {
}//end of catch
}//end of ru()
};//end of thread
t.start();//starting the thread
}//end of else
}//end of first if
} //命令操作结束
//defining sendPhone method
public void sendPhone() throws IOException {
System.out.println("ken de man");//check
HttpConnection http = null;//HttpConnection variable
OutputStream oStrm = null;//OutputStream variable
InputStream iStrm = null;//InputStream variable
//String url = "http://10.100.29.15:8080/www/serv" + "?" + "code=" + codeField.getString();//server url and parameters
String url = "http://localhost:8080/www/serv" + "?" + "code=" + codeField.getString();//server url and parameters
try {
http = (HttpConnection) Connector.open(url);//opening connection
System.out.println("connection made");//checking code
//oStrm = http.openOutputStream();//opening output stream
http.setRequestMethod(HttpConnection.GET);//setting request type
//http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
//byte data[] = ("phone=" + phoneField.getString()).getBytes();
//oStrm.write(data);
iStrm = http.openInputStream();//openning input stream
if (http.getResponseCode() == HttpConnection.HTTP_OK) {//if the connection is ok
int length = (int) http.getLength();
String str;
if (length != -1) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
} else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) {
bStrm.write(ch);
}
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("de man");
System.out.println(str);
int x = str.length();
System.out.println(x);
if (str.equals("ok")) {
track = codeField.getString();
codeField.setString("");//emptying textfield
mainMenu = new List("", Choice.IMPLICIT);//creating a list object
mainMenu.append("Vote", null);
mainMenu.append("Results", null);
quCmd = new Command("Quit", Command.EXIT, 0);//creating a quit command on the list
okCmd = new Command("Ok", Command.OK, 0);//creating an ok command on the list
mainMenu.addCommand(okCmd);//adding ok command
mainMenu.addCommand(quCmd);//adding quit command
mainMenu.setSelectCommand(okCmd);//setting the default select command
mainMenu.setCommandListener(this);//setting the command listener
display.setCurrent(mainMenu);
} else {
//add error message to phone_error stingItem
codeField.setString("");//emptying textfield
codeError.setText("Wrong code, please enter right code");
display.setCurrent(welForm);
}
}
} catch (Exception e) {
} finally {
if (iStrm != null) {
iStrm.close();
}
if (http != null) {
http.close();
}
}
}
} //课程结束
servlet:
导入java.io. ; //用于io类的包
import javax.servlet.ServletException; //用于servlet异常类的包
import javax.servlet.http。;
import java.sql。*; //用于sql类的包
/ ** * * @author k'owino * / public class serv扩展了HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//declaring variables
PrintWriter pw;//PrintWriter object
String vcode;//code parameter sent from client
Connection con = null;//connection variable
String dbDriver = "com.mysql.jdbc.Driver";//the database driver
String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
String dbUser = "root";//database user
String dbPwd = "";//database password
PreparedStatement pstmt = null;//Prepared statement variable
String query = "select * from student where vote_code = ?;";//the query to select code from db
ResultSet rs = null;//resultset variable
String dbCode = null;//code from database
//getting the "phone" parameter sent from client
vcode = req.getParameter("code");//getting the "code" parameter sent from voter
//vcode = "345qwert";
//setting the content type of the response
res.setContentType("text/plain");
//creating a PrintWriter object
pw = res.getWriter();//getting a writer
//pw.println("ken");
try {//trying to load the database driver and establish a connection to the database
Class.forName(dbDriver);//loading the database driver
con = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//establishing a connection to the database
//pw.println("connection established");//output if connection is established
} catch (Exception e) {
e.printStackTrace(pw);//printing the exception error trace to the writer
}
//trying to query the database
try {
pstmt = con.prepareStatement(query);//preparing a statement
pstmt.setString(1, vcode);//setting the input parameter
rs = pstmt.executeQuery();//executing the query assigning to the resultset object
//pw.println("ken");
//extracring data from the resultset
while (rs.next()) {
dbCode = rs.getString("vote_code");//getting the code from database
//pw.println(dbPhone);
}//end of while
if (vcode.equals(dbCode)) {
pw.print("ok");//printing ok if code mataches
} else {
pw.print("error");//printing error if code doesn't match
}
//pw.println("yeah");
} catch (Exception e) {
e.printStackTrace(pw);//sending the error
}
finally{
if(pw !=null){
pw.close();
}
}
}
}`没有错误。在模拟器中工作正常但在手机上无法连接到servlet。
答案 0 :(得分:0)
我猜你的调制解调器给你的网址是http://10.100.29.15 该地址不是公共地址,而是private block,这意味着只有连接到调制解调器所连接的同一网络的人才能访问该地址。为了使测试起作用,您应该通过WiFi将手机连接到同一个调制解调器。这是有效的,因为手机将在同一个私人区块中找到服务器。我已经好几次做过了。
另一个难以开始工作的选择是port forwarding。如果您的ISP为您的调制解调器提供公共Internet地址并可以转发端口,请选择任何端口转发到您的计算机。这样,您就可以从任何连接到Internet的设备连接到您的服务器,直到您的ISP为您的调制解调器分配不同的公共地址。