3

Hi I am developing android app using java restfull webservices Here I am getting one issue in calling web service through post method when I use client.post("") my all values get null while calling webservice. I dont know why it is happening. And when I use client.get("") its working properly.And I am able to do register properly through client.get. But I want to use client.post Please help me let me know what I am mistaking.

public void registerUser(View view){

    String name = nameET.getText().toString();

    String email = emailET.getText().toString();

    String password = pwdET.getText().toString();

    RequestParams params = new RequestParams();

    if(Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)){

        if(Utility.validate(email)){
            control
            params.put("name", name);

            params.put("username", email);

            params.put("password", password);
            // Invoke RESTful Web Service with Http parameters
            invokeWS(params);
        }
   }

public void invokeWS(RequestParams params){
    System.out.println("params=====  "+params);

    prgDialog.show();

**AsyncHttpClient client = new AsyncHttpClient();
    client.post("http://localhost:8080/DemoForAndroid/register/doregister",params ,new AsyncHttpResponseHandler()** {
        // When the response returned by REST has Http response code '200'
         public void onSuccess(String response) {
            // Hide Progress Dialog
             System.out.println("response=======   "+response);
             prgDialog.hide();
             try {
                      // JSON Object
                     JSONObject obj = new JSONObject(response);
                     // When the JSON response has status boolean value assigned with true
                     if(obj.getBoolean("status")){
                         // Set Default Values for Edit View controls
                         setDefaultValues();
                         // Display successfully registered message using Toast
                         Toast.makeText(getApplicationContext(), "You are successfully registered!", Toast.LENGTH_LONG).show();
                     }
                     // Else display error message
                     else{
                         errorMsg.setText(obj.getString("error_msg"));
                         Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                     }
             } catch (JSONException e) {
                 // TODO Auto-generated catch block
                 Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                 e.printStackTrace();

             }
         }
         // When the response returned by REST has Http response code other than '200'
         public void onFailure(int statusCode, Throwable error,
             String content) {
             // Hide Progress Dialog
             prgDialog.hide();
             // When Http response code is '404'
             if(statusCode == 404){
                 Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
             }
             // When Http response code is '500'
             else if(statusCode == 500){
                 Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
             }
             // When Http response code other than 404, 500
             else{
                 Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
             }
         }
     });

    System.out.println("Client=======  "+client);
}

log file

01-28 12:10:26.307: W/KeyCharacterMap(106): No keyboard for id 0
01-28 12:10:26.307: W/KeyCharacterMap(106): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
01-28 12:11:33.238: I/System.out(274): params=====  username=raju@mail.com&name=Raju &password=123456
01-28 12:11:33.328: D/dalvikvm(274): GC_FOR_MALLOC freed 5941 objects / 275504 bytes in 57ms
01-28 12:11:33.378: I/System.out(274): Client=======  com.loopj.android.http.AsyncHttpClient@44ef5638
01-28 12:11:33.578: I/System.out(274): response=======   {"tag":"register","status":false,"error_msg":"Error occured"}
01-28 12:11:33.678: I/ARMAssembler(58): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x360af8:0x360bb4] in 405396 ns
01-28 12:11:33.745: W/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@450aa070

Restful Webservice code

@Path("/register")
public class Register {
 // HTTP Get Method
 User usr = new User();
@POST
// Path: http://localhost/<appln-folder-name>/register/doregister
@Path("/doregister") 
// Produces JSON as response
@Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/register/doregister?name=pqrs&username=abc&password=xyz

public String doLogin(@QueryParam("name") String name, @QueryParam("username") String uname, @QueryParam("password") String pwd){
    String response = "";
    System.out.println("Inside doLogin "+uname+"  "+pwd);
    int retCode = registerUser(name, uname, pwd);
    System.out.println("ret code= "+retCode);
    if(retCode == 0){
        response = Utitlity.constructJSON("register",true);
    }else if(retCode == 1){
        response = Utitlity.constructJSON("register",false, "You are already registered");
    }else if(retCode == 2){
        response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
    }else if(retCode == 3){
        response = Utitlity.constructJSON("register",false, "Error occured");
    }
    return response;

}

private int registerUser(String name, String uname, String pwd){
    System.out.println("Inside checkCredentials");
    System.out.println("name= "+name);
    System.out.println("uname= "+uname);
    System.out.println("pwd= "+pwd);
    int result = 3;
    if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
        try {
            System.out.println("add user---------------");
           /* if(DBConnection.insertUser(name, uname, pwd)){*/
                usr.setName(name);
                usr.setUsername(uname);
                usr.setPassword(pwd);
                new UserDao().addUser(usr);

                System.out.println("RegisterUSer if");
                result = 0;
       /*     }*/
        } /*catch(SQLException sqle){
            System.out.println("RegisterUSer catch sqle");
            //When Primary key violation occurs that means user is already registered
            if(sqle.getErrorCode() == 1062){
                result = 1;
            }
            //When special characters are used in name,username or password
            else if(sqle.getErrorCode() == 1064){
                System.out.println(sqle.getErrorCode());
                result = 2;
            }
        }*/
        catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Inside checkCredentials catch e ");
            result = 3;
        }
    }else{
        System.out.println("Inside checkCredentials else");
        result = 3;
    }

    return result;
}
}

webservice log

Inside doLogin null  null
Inside checkCredentials
name= null
uname= null
pwd= null
Inside isNotNull
Inside checkCredentials else
ret code= 3
  • Try to add the following annotation `@Consumes(MediaType.APPLICATION_FORM_URLENCODED)` above `doLogin()`. More info [here](http://stackoverflow.com/questions/8194408/how-to-access-parameters-in-a-restful-post-method) and [here](http://stackoverflow.com/questions/10357041/jersey-post-method-is-receiving-null-values-as-parameters) – Nir Alfasi Jan 28 '15 at 07:52
  • @alfasin hey I add this annotation also but its not working. – Harshit Agarwal Jan 28 '15 at 07:58
  • @Yazan hey its working thanks.. Please vote my question if it is correct – Harshit Agarwal Jan 28 '15 at 08:09

1 Answers1

4

replace @QueryParam with @FormParam in doLogin() i think @QueryParam will be more like a GET param expected.

Yazan
  • 5,966
  • 1
  • 16
  • 32