【问题标题】:HttpServlet Receive Null in doPost() from Android ClientHttpServlet 在 doPost() 中从 Android 客户端接收 Null
【发布时间】:2012-10-11 17:02:19
【问题描述】:

我正在尝试将一些数据从 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' 什么也没收到。请告诉我如何解决这个问题。

问候,

【问题讨论】:

  • 我不确定您具体问什么。您似乎已经对需求进行了观察和陈述。我现在能想到的就是,“好吧,只需相应地编写代码”。但这会使整个问题完全无用。请详细说明具体问题。在相应地编写代码时,你到底卡在哪里了?
  • 我还是不明白具体的问题。只需放置一个if 块来检查是否从客户端接收到数据,然后仅在条件为真时执行查询?如果它实际上比这更复杂,那么你真的需要详细说明。我们不能神奇地传送到您的位置以便自己查看您的代码。编辑问题并包含一些清楚地表明问题的具体代码将非常有助于更好地理解您的具体问题。
  • 您在编辑过程中添加的问题又很奇怪。保持doPost() 方法等待直到设置请求属性?当当前线程基本上代表 HTTP 请求本身时,这怎么可能呢?您实际上不是指会话属性吗?在提出概念上错误的问题之前,您可能需要花更多的时间来学习基本的 HTTP 和 servlet 是如何工作的。这些帖子可能会有所帮助:stackoverflow.com/a/3106909stackoverflow.com/q/2793150 正确掌握基本概念后,请改进问题。
  • 还是看不懂吗?

标签: android jakarta-ee servlets


【解决方案1】:

您的 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 文件。这感觉太像“roseindia.net-sn-p”了。如果您确实在阅读那个糟糕的网站,请从现在开始将其列入终身黑名单。

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

  1. Using HttpClient API
  2. Using URLConnection API

你应该选择其中一个并坚持下去。上面的链接指向 Stack Overflow 答案风格的具体示例。

【讨论】:

  • 嗨,Balusc,我没有从 roseindia 阅读任何内容。如果我有一些问题,我会来这里:) 无论如何,在您使用 HttpClient API 而不是 URLConnection 回答之前,我已经更改了我的 android 客户端代码。它现在工作正常:)。感谢您的帮助和支持,但我还有一个问题,为什么它在设计技术上不好?
  • 嗨 BalusC,您能否详细说明一下为什么 servlet 设计在技术上不行?
猜你喜欢
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2014-08-29
  • 2015-10-21
  • 1970-01-01
  • 2013-04-20
相关资源
最近更新 更多