Java me J2ME http post错误-诺基亚Asha SDK 1.0

Java me J2ME http post错误-诺基亚Asha SDK 1.0,java-me,http-post,nokia-s40,Java Me,Http Post,Nokia S40,我正在从我的J2ME应用程序向诺基亚Asha 501(s40)发出http post请求。我正在使用诺基亚Asha SDK 1.0进行开发 一旦应用程序尝试建立http连接,它将直接进入try-catch语句的finally子句,而不会抛出任何异常 在emulator中,将显示以下消息-“运行此应用程序时出现问题”—— 然后,我尝试了诺基亚开发者论坛中给出的示例http post源代码,得到了相同的结果 代码如下所示 import javax.microedition.midlet.*; imp

我正在从我的J2ME应用程序向诺基亚Asha 501(s40)发出http post请求。我正在使用诺基亚Asha SDK 1.0进行开发

一旦应用程序尝试建立http连接,它将直接进入try-catch语句的finally子句,而不会抛出任何异常

在emulator中,将显示以下消息-“运行此应用程序时出现问题”——

然后,我尝试了诺基亚开发者论坛中给出的示例http post源代码,得到了相同的结果

代码如下所示

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*; 

public class HttpPOST extends MIDlet implements CommandListener {

private static String defaultURL = "http://localhost/api/signin"; 

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 HttpPOST()
{
    myDisplay = Display.getDisplay(this);
mainScreen = new Form("Type in a URL:");
requestField = new TextField(null, defaultURL, 100, TextField.URL);
mainScreen.append(requestField);
mainScreen.addCommand(sendCommand);
mainScreen.setCommandListener(this);
}

public void startApp() {myDisplay.setCurrent(mainScreen);}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) 
{ 
if (c == sendCommand) 
{
    String urlstring = requestField.getString();

    String resultstring = sendPostRequest(urlstring);

    resultScreen = new Form("POST Result:");
    resultField = new StringItem(null, resultstring);
    resultScreen.append(resultField);
    resultScreen.addCommand(backCommand);
    resultScreen.setCommandListener(this);
    myDisplay.setCurrent(resultScreen);

} 
else if (c == backCommand) 
{
    requestField.setString(defaultURL);
    myDisplay.setCurrent(mainScreen); 
}
}

public String sendPostRequest(String urlstring) 
{
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;

String message = "";

String requeststring = "email=test@gmail.com&password=1234";
try 
{
    hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE);

    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]);
    }
    // flush outdos.flush();

    dis = new DataInputStream(hc.openInputStream());

    int ch;
    while ((ch = dis.read()) != -1) 
    {
        message = message + (char) ch;
    }

}
catch (IOException ioe) 
{
    message = "ERROR";
} 
finally 
{
    try 
    { 
        if (hc != null) 
            hc.close();
    }
    catch (IOException ignored) 
    {
    }
    try 
    { 
        if (dis != null) 
            dis.close();
    } 
    catch (IOException ignored) 
    {
    } 
    try 
    { 
        if (dos != null) 
            dos.close();
    } 
    catch (IOException ignored) 
    {
    } 
}
return message;
}
}
import javax.microedition.midlet.*;
导入javax.microedition.lcdui.*;
导入javax.microedition.io.*;
导入java.io.*;
公共类HttpPOST扩展MIDlet实现CommandListener{
私有静态字符串defaultURL=”http://localhost/api/signin"; 
私有显示myDisplay=null;
私有窗体主屏幕;
私有文本字段请求字段;
私有形式结果筛选;
私有StringItem结果字段;
Command sendCommand=新命令(“发送”,Command.OK,1);
命令backCommand=新命令(“BACK”,Command.OK,1);
公共HttpPOST()
{
myDisplay=Display.getDisplay(这个);
mainScreen=新表单(“键入URL:”);
requestField=newtextfield(null,defaultURL,100,TextField.URL);
mainScreen.append(请求字段);
mainScreen.addCommand(sendCommand);
mainScreen.setCommandListener(此);
}
public void startApp(){myDisplay.setCurrent(主屏幕);}
public void pauseApp(){}
公共应用程序(布尔无条件){}
公共无效命令操作(命令c,可显示)
{ 
if(c==sendCommand)
{
字符串urlstring=requestField.getString();
String resultstring=sendPostRequest(urlstring);
resultScreen=新表单(“结果发布:”);
resultField=新的StringItem(null,resultstring);
resultScreen.append(resultField);
resultScreen.addCommand(backCommand);
resultScreen.setCommandListener(这个);
myDisplay.setCurrent(resultScreen);
} 
else if(c==backCommand)
{
requestField.setString(defaultURL);
myDisplay.setCurrent(主屏幕);
}
}
公共字符串sendPostRequest(字符串urlstring)
{
HttpConnection hc=null;
DataInputStream dis=null;
DataOutputStream dos=null;
字符串消息=”;
String requeststring=“电子邮件=test@gmail.com&密码=1234”;
尝试
{
hc=(HttpConnection)Connector.open(urlstring,Connector.READ\u WRITE);
setRequestMethod(HttpConnection.POST);
dos=hc.openDataOutputStream();
byte[]request_body=requeststring.getBytes();
for(int i=0;i
有人请帮我解决这个问题


提前感谢。

请查看下面的示例。这对某人有帮助。它在诺基亚Asha 501中经过测试,工作正常

  import javax.microedition.midlet.*;
  import javax.microedition.lcdui.*;
  import javax.microedition.io.*;
  import java.io.*;

  public class GetNpost extends MIDlet implements CommandListener
  {
private Display display;      // Reference to Display object
private Form fmMain;         // The main form
private Alert alError;       // Alert to error message
private Command cmGET;       // Request method GET
private Command cmPOST;      // Request method Post  
private Command cmExit;      // Command to exit the MIDlet
private TextField tfAcct;    // Get account number
private TextField tfPwd;     // Get password
private StringItem siBalance;// Show account balance
private String errorMsg = null;


GetNetworkConnection getObject = null;
PostNetworkConnection postObject = null;

GetNpost  mainObject = null;

public GetNpost()
{
    display = Display.getDisplay(this);

    mainObject = this;


    // Create commands
    cmGET = new Command("GET", Command.SCREEN, 2);
    cmPOST = new Command("POST", Command.SCREEN, 3);    
    cmExit = new Command("Exit", Command.EXIT, 1);

    // Textfields
    tfAcct = new TextField("Account:", "", 5, TextField.NUMERIC);
    tfPwd = new TextField("Password:", "", 10, TextField.ANY | TextField.PASSWORD);        

    // Balance string item
    siBalance = new StringItem("Balance: $", "");

    // Create Form, add commands & componenets, listen for events
    fmMain = new Form("Account Information");    
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmGET);
    fmMain.addCommand(cmPOST);

    fmMain.append(tfAcct);
    fmMain.append(tfPwd);
    fmMain.append(siBalance);

    fmMain.setCommandListener(this);   
}

public void startApp()
{
    display.setCurrent(fmMain);
}

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command c, Displayable s)
{
    if (c == cmGET || c == cmPOST)
    {
        try 
        {
            if (c == cmGET){               
                getObject = new GetNetworkConnection();
                getObject.start();           
            }
            else{
                postObject = new PostNetworkConnection();
                postObject.start();          
            }
        }
        catch (Exception e)
        { 
            System.err.println("Msg: " + e.toString());
        }
    }
    else if (c == cmExit)
    {
        destroyApp(false);
        notifyDestroyed();
    } 
}

/*--------------------------------------------------
 * Access servlet using GET
 *-------------------------------------------------*/    
private void lookupBalance_withGET() throws IOException
{
    HttpConnection http = null;
    InputStream iStrm = null;    
    boolean ret = false;

    // Data is passed at the end of url for GET
    // don't use localhost as a ip
    String url = "http://(ip address):(port)/ServerSide/hello" + "?" +        
            "account=" + tfAcct.getString() + "&" + 
            "password=" + tfPwd.getString();


    try
    {
        http = (HttpConnection) Connector.open(url);

        //----------------
        // Client Request
        //----------------
        // 1) Send request method
        http.setRequestMethod(HttpConnection.GET);
        // 2) Send header information - none
        // 3) Send body/data -  data is at the end of URL

        //----------------
        // Server Response
        //----------------
        iStrm = http.openInputStream();      
        // Three steps are processed in this method call
        ret = processServerResponse(http, iStrm);
    }
    finally
    {
        // Clean up
        if (iStrm != null)
            iStrm.close();
        if (http != null)
            http.close();
    }

    // Process request failed, show alert    
    if (ret == false)
        showAlert(errorMsg);        
}

/*--------------------------------------------------
 * Access servlet using POST
 *-------------------------------------------------*/  
private void lookupBalance_withPOST() throws IOException
{
    HttpConnection http = null;
    OutputStream oStrm = null;
    InputStream iStrm = null;    
    boolean ret = false;

    // Data is passed as a separate stream for POST (below)
    // don't use localhost as a ip
    String url = "http://(ip address):(port)/ServerSide/hello";   



    try
    {
        http = (HttpConnection) Connector.open(url);                    

        //----------------
        // Client Request
        //----------------
        // 1) Send request type
        http.setRequestMethod(HttpConnection.POST); 

        // 2) Send header information. Required for POST to work!
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


        oStrm = http.openOutputStream();      

        // If you experience connection/IO problems, try 
        // removing the comment from the following line
        //         http.setRequestProperty("Connection", "close");      

        // 3) Send data/body
        // Write account number
        byte data[] = ("account=" + tfAcct.getString()).getBytes();
        oStrm.write(data);

        // Write password
        data = ("&password=" + tfPwd.getString()).getBytes();
        oStrm.write(data);

        // For 1.0.3 remove flush command
        // See the note at the bottom of this file
        //      oStrm.flush();

        //----------------
        // Server Response
        //----------------
        iStrm = http.openInputStream();      
        // Three steps are processed in this method call      
        ret = processServerResponse(http, iStrm);
    }

    catch(Exception e){
        System.out.println("Error in Post: "+e.getMessage());
    }

    finally
    {
        // Clean up
        if (iStrm != null)
            iStrm.close();
        if (oStrm != null)
            oStrm.close();        
        if (http != null)
            http.close();
    }

    // Process request failed, show alert    
    if (ret == false)
        showAlert(errorMsg);        





}

/*--------------------------------------------------
 * Process a response from a server
 *-------------------------------------------------*/
private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException
{
    //Reset error message
    errorMsg = null;

    // 1) Get status Line
    if (http.getResponseCode() == HttpConnection.HTTP_OK)
    {
        // 2) Get header information - none

        // 3) Get body (data)
        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();
        }

        // Update the string item on the display
        siBalance.setText(str);
        return true;

    }
    else
        // Use message from the servlet
        errorMsg = new String( http.getResponseMessage());

    return false;      
}

/*--------------------------------------------------
 * Show an Alert
 *-------------------------------------------------*/
private void showAlert(String msg)
{
    // Create Alert, use message returned from servlet
    alError = new Alert("Error", msg, null, AlertType.ERROR);

    // Set Alert to type Modal
    alError.setTimeout(Alert.FOREVER);

    // Display the Alert. Once dismissed, display the form
    display.setCurrent(alError, fmMain);            
}


public class GetNetworkConnection extends Thread{
    public void run(){
        try {
            mainObject.lookupBalance_withGET();
        }
        catch(Exception e){
            System.out.println("Error in Get Connection: "+e.getMessage());
        }
    }
}


public class PostNetworkConnection extends Thread{
    public void run(){
        try {
            mainObject.lookupBalance_withPOST();
        }
        catch(Exception e){
            System.out.println("Error in Post Connection: "+e.getMessage());
        }
    }
}


}
服务器端代码是,(它是一个servlet,名称是hello.java)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author thirumalvalavan
 */
@WebServlet(name = "hello", urlPatterns = {"/hello"})
public class hello extends HttpServlet {

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        // /*TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet hello</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet hello at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
        // */
    } finally {
        out.close();
    }
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
//        processRequest(request, response);

    String acct = request.getParameter("account"),
            pwd = request.getParameter("password");

    System.out.println("Hello Get Method::: " + acct + " " + pwd);

    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet hello</title>");
    out.println("</head>");
    out.println("<body>");
    out.print("<h1>Hi Get Method: </h1> <br> <h2> Your Account is: " + acct + "<br>   Your pwd is: " + pwd + "</h2>");
    out.println("</body>");
    out.println("</html>");
    out.close();
}

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
//        processRequest(request, response);

    String acct = request.getParameter("account"),
            pwd = request.getParameter("password");

    System.out.println("Hello Post Method::: " + acct + " " + pwd);

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet hello</title>");
    out.println("</head>");
    out.println("<body>");
    out.print("<h1>Hi Post Method: </h1> <br> <h2> Your Account is: " + acct + "<br> Your pwd is: " + pwd + "</h2>");
    out.println("</body>");
    out.println("</html>");
    out.close();

}

/** 
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>
}