-1

I am trying to send some data from Android Client to HttpServlet. My Servlet code is as follows

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();
                }
            }
    }
}

and my android code is

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();
        }

}

}

The problem is that when I run the 'Servlet' I get output 'Servlet Started First Time' which is OK but when I run my android client and write some data in EditText fields and press register button nothing happens. 'Servlet' receive nothing. Please let me know how can I solve this problem.

Regards,

Java Developer
  • 123
  • 2
  • 10
  • 3
    I'm not sure what you're concretely *asking*. You seem to have made an observation and a statement about a requirement. All I can think of now is, "Well, just write code accordingly". But that would make the whole question completely useless. Please elaborate the concrete problem in more detail. Where exactly are you stucking while writing code accordingly? – BalusC Oct 21 '12 at 21:10
  • 1
    I do still not understand the concrete problem. Just put an `if` block which checks if the data is received from the client and then execute the query only if the condition is true? If it's actually more complicated than that, then you really need to elaborate more. We can't magically beam over to your location in order to see your code ourselves. Editing the question and including some concrete code which clearly demonstrates the problem would be very helpful in better understanding your concrete problem. – BalusC Oct 21 '12 at 23:50
  • 1
    The question which you've added during edit is in turn very strange. Keep `doPost()` method on wait until a request attribute is set? How is that ever possible when the current thread basically represents the HTTP request itself? Don't you actually mean a session attribute instead? Perhaps you need to invest some more time in learning how basic HTTP and servlets work before asking conceptually wrong questions. Those posts may be helpful then: http://stackoverflow.com/a/3106909 and http://stackoverflow.com/q/2793150 Once you have properly grasped the basic concepts, improve the question. – BalusC Oct 22 '12 at 20:37
  • Is it still not understandable ? – Java Developer Nov 11 '12 at 01:16

1 Answers1

0

Your servlet looks functionally okay (design-technically not, but that's a different matter). Your Android side looks however definitely not good.

This,

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

is how you would be preparing request parameters before sending the HTTP request using the Android-builtin Apache HttpClient API.

But here,

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();

you're however sending the HTTP request using the Java SE builtin URLConnection API instead. And then actually in a bad way; you're not sending a proper application/x-www-form-urlendocded query string, but instead a single string value in the platform default encoding. Also the DataOutputStream makes completely no sense in this context, you're not creating a .dat file at all. This feels too much like a "roseindia.net-snippet". If you were indeed reading that terrible site, please put it in a lifetime blacklist from now on.

It look like that you're mixing different approaches of sending a HTTP POST request in Android.

  1. Using HttpClient API
  2. Using URLConnection API

You should choose the one or the other and stick to it. The above links point to concrete examples in flavor of a Stack Overflow answer.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Hi Balusc, I am not reading anything from roseindia. If I have some question I come to here :) anyways I have changed my android client code before your answer with HttpClient API instead of URLConnection. Its working fine now :). Thanks for your help and support, but I have one more question, why it is design-technically not good ? – Java Developer Nov 12 '12 at 11:39
  • Hi BalusC, Could you please elaborate a bit more why the servlet design-technically not OK ? – Java Developer Nov 12 '12 at 11:48