java - Post 方法在 Android 的 AsyncHttpClient 中不起作用

标签 java android web-services rest

您好,我正在使用 java restfull webservices 开发 android 应用程序在这里,当我使用 client.post("") 时,我在通过 post 方法调用 Web 服务时遇到了一个问题,我的所有值在调用时都为空网络服务。我不知道为什么会这样。当我使用 client.get("") 时,它的工作正常。我能够通过 client.get 正确注册。 但我想使用 client.post 请帮助我让我知道我的错误。

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

日志文件

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 Web 服务代码

@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;
}
}

网络服务日志

Inside doLogin null  null
Inside checkCredentials
name= null
uname= null
pwd= null
Inside isNotNull
Inside checkCredentials else
ret code= 3

最佳答案

doLogin()中用@FormParam替换@QueryParam 我认为 @QueryParam 将更像是预期的 GET 参数。

关于java - Post 方法在 Android 的 AsyncHttpClient 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28186893/

相关文章:

java - 是否可以混合 Eclipse 项目类型?

java - 信号量函数中的死锁

java - 如果两个项目具有相同的图像,则在运行时删除 GridView 项目

java - Jersey 内容类型定制

java - 将列表序列化为 json 时出现异常

android - 多个 APK 规则..?

android - 找不到 OnCameraIdleListener(不推荐使用 OnCameraChangeListener())_Android 工作室?

.net - 当尝试对引用 Web 服务的类进行单元测试时,我在这里做错了什么

java - 如何连接到 SOAP/WSDL Web 服务?

java - 无法从 URL 获取 JSONObject