HttpServlet在Android客户端的doPost()中接收Null

时间:2012-10-21 20:48:53

标签: android java-ee servlets

我正在尝试从Android客户端向HttpServlet发送一些数据。我的Servlet代码如下

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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


public class DBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection connection= null;   

/**
 * @see HttpServlet#HttpServlet()
 */
public DBServlet() {
        super();
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {

    doPost(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    if(request.getParameterNames().hasMoreElements()){
                insertRecord(request, getDbConnection());
            }
            else{ System.out.println("Servlet Started First Time"); }



}

/**
 * Return database connection
 * @return
 */
private Connection getDbConnection(){
        String connectionURL = "jdbc:mysql://127.0.0.1:3306/testDB";

        try {

            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectionURL, "root", "");

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return connection;  
}

/**
 * Insert record in database
 * @param request
 * @param connection
 */
private void insertRecord(HttpServletRequest request, Connection connection){   

            System.out.println("===== Received Record =====");

            PreparedStatement stmt;

            try {
                stmt = connection.prepareStatement("insert into users(Name,email,password) values(?,?,?)");
                stmt.setString(1, request.getParameter("name"));
                stmt.setString(2, request.getParameter("e-mail"));
                stmt.setString(3, request.getParameter("password"));

                int i= stmt.executeUpdate();

                if(i != 0){
                    System.out.println("data inserted !!!");
                }
                else{
                    System.out.println("data failed to insert");
                }

            } catch (SQLException e) {
                e.printStackTrace();
            }

            finally{

                try {
                    connection.close();
                } catch (SQLException e) {

                    e.printStackTrace();
                }
            }
    }
}

我的安卓代码是

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;

import org.apache.http.message.BasicNameValuePair;

import com.example.messenger.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SignUp extends Activity {

Button register;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sign_up);

    register = (Button)findViewById(R.id.register);

    register.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.v("OnClick", "=== onClick ===");
            registerUser();

        }
    });
}

@SuppressLint({ "NewApi", "NewApi", "NewApi" })
private void registerUser(){


        String name= ((EditText)findViewById(R.id.name)).getText().toString();
        String email= ((EditText)findViewById(R.id.email)).getText().toString();
        String password= ((EditText)findViewById(R.id.password)).getText().toString();

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("name", name));
        nameValuePairs.add(new BasicNameValuePair("email", email));
        nameValuePairs.add(new BasicNameValuePair("password", password));


        try {

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            URL url=new URL("http://192.168.1.10:8080/DBservlet/DBServlet");
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setDoOutput(true);
            con.setRequestMethod("POST");
            DataOutputStream dos=new DataOutputStream(con.getOutputStream());
            dos.writeBytes(name);
            dos.flush();
            dos.close();

}  catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

}

问题是,当我运行'Servlet'时,我得到输出'Servlet Started First Time',这是正常的但是当我运行我的Android客户端并在EditText字段中写入一些数据并按下注册按钮时没有任何反应。 'Servlet'什么也得不到。请让我知道如何解决这个问题。

此致

1 个答案:

答案 0 :(得分:0)

你的servlet看起来功能正常(设计技术上没有,但这是另一回事)。你的Android方面看起来肯定不好。

这,

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("password", password));

是在使用Android内置Apache HttpClient API发送HTTP请求之前准备请求参数的方法。

但是,

URL url=new URL("http://192.168.1.10:8080/DBservlet/DBServlet");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
DataOutputStream dos=new DataOutputStream(con.getOutputStream());
dos.writeBytes(name);
dos.flush();
dos.close();

然而,您使用Java SE内置URLConnection API发送HTTP请求。然后实际上是一个糟糕的方式;您没有发送正确的application/x-www-form-urlendocded查询字符串,而是发送平台默认编码中的单个字符串值。此外,DataOutputStream在此上下文中完全没有意义,您根本不会创建.dat文件。这感觉太像一个&#34; roseindia.net-snippet&#34;。如果您确实正在阅读那个可怕的网站,请从现在开始将其列入终身黑名单。

您似乎正在混合在Android中发送HTTP POST请求的不同方法。

  1. Using HttpClient API
  2. Using URLConnection API
  3. 你应该选择其中一个并坚持下去。上面的链接指出了Stack Overflow答案风格的具体例子。