代码之家  ›  专栏  ›  技术社区  ›  ahmed jallad

调用post方法时获取响应

  •  -1
  • ahmed jallad  · 技术社区  · 7 年前

    我希望能够处理调用post方法时收到的响应,我在postman中测试了post方法,它运行良好并返回以下结果:

     [
    {
        "messagetitle": "success",
        "response": {
            "tblRegisteredUsers_UserPKID": 2013,
            "tblRegisteredUsers_UserName": "hi",
            "tblRegisteredUsers_Password": "hi",
            "tblRegisteredUsers_FirstName": "ahmed",
            "tblRegisteredUsers_SecondName": "mahmoud\n",
            "tblRegisteredUsers_LastName": "jallad",
            "tblRegisteredUsers_Country": "أردني",
            "tblRegisteredUsers_City": null,
            "tblRegisteredUsers_Gender": null,
            "tblRegisteredUsers_BirthDate": null,
            "tblRegisteredUsers_Education": null,
            "tblRegisteredUsers_Job": null,
            "tblRegisteredUsers_HomePhone": null,
            "tblRegisteredUsers_MobileNumber": "656",
            "tblRegisteredUsers_FaxNumber": null,
            "tblRegisteredUsers_Email": "gmail",
            "tblRegisteredUsers_HowYouKnowUS": null,
            "tblRegisteredUsers_Nationality": "أردني",
            "tblRegisteredUsers_Active": false,
            "tblRegisteredUsers_PayType": "Knet",
            "tblRegisteredUsers_photo": null,
            "tblRegisteredUsers_DraftInfo": "Knet",
            "tblRegisteredUsers_AccountStates": "pending",
            "tblRegisteredUsers_registrationDate": "2017-12-08T15:21:47",
            "tblRegisteredUsers_nickName": "jallad93",
            "tblRegisteredUsers_Activeby_FKID": -1,
            "tblRegisteredUsers_ActivationDate": null,
            "tblRegisteredUsers_Year": 1,
            "tblRegisteredUsers_ActivebyPayment": false,
            "tblRegisteredUsers_intensified": false,
            "tblRegisteredUsers_Shiping_Address": null,
            "tblRegisteredUsers_intensified_Status": null,
            "tblRegisteredUsers_ReactivationDateTime": null,
            "tblRegisteredUsers_ActivebyPayment_Intensive": null,
            "tblRegisteredUsers_ActivationDate_IntensiveChange": null,
            "tblRegisteredUsers_Installment": null,
            "tblRegisteredUsers_InstallmentActivationDate": null,
            "tblRegisteredUsers_Installment_ActivePayment": null,
            "tblRegisteredUsers_Hide": null,
            "tblRegisteredUsers_Hide_User_FK_ID": null,
            "tblRegisteredUsers_Hide_DateTime": null,
            "tblRegisteredUsers_Renew_Datetime": null
        }
    }
    

    ] 另一方面,如果登录信息不正确,我会得到如下响应:

     [
    {
        "messagetitle": "username or password is incorrect",
        "response": null
    }
    

    ] 我希望能够检查登录是否成功用户登录并将其所有信息存储在变量中,以下是我的android代码:

     signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    RequestQueue requestQueue = Volley.newRequestQueue(SignIn.this);
                    String URL = "http://localhost/WebApplication7/api/login";
                    JSONObject jsonBody = new JSONObject();
                   // jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
                    jsonBody.put("tblRegisteredUsers_UserName", username.getText().toString().trim());
                    jsonBody.put("tblRegisteredUsers_Password", password.getText().toString().trim());
    
    
    
                    final String requestBody = jsonBody.toString();
    
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
    
                            if (response.equals("username or password is incorrect")) {
                                //login authenticated. Start the next activity of your app
                                Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                               // Toast.makeText(getApplicationContext(), "registered successfully ", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                            } else {
                                //login failed. prompt to re-enter the credentials
                                Toast.makeText(SignIn.this, "Failed to log In", Toast.LENGTH_SHORT).show();
    
                                Log.i("VOLLEY", response);
                                Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("VOLLEY", error.toString());
                        }
                    })
    
                    {
                        @Override
                        public String getBodyContentType() {
                            return "application/json; charset=utf-8";
                        }
    
                        @Override
                        public byte[] getBody() throws AuthFailureError {
                            try {
                                return requestBody == null ? null : requestBody.getBytes("utf-8");
                            } catch (UnsupportedEncodingException uee) {
                                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                                return null;
                            }
                        }
    
                        @Override
                        protected Response<String> parseNetworkResponse(NetworkResponse response) {
                            String responseString;
                            String json = null;
                            try {
                                json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            responseString = String.valueOf(json).trim();
    
                            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                        }
                    };
    
                    requestQueue.add(stringRequest);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
    
            }
        });
    
        }  
    

    我在响应中得到的是一个包含所有信息的字符串,我总是得到登录失败。它将响应视为一个字符串。很多帖子都在谈论jsonarrayrequest,但我不知道如何在我的案例中实现它

    1 回复  |  直到 7 年前
        1
  •  0
  •   Rudrik Patel    7 年前

    使用变量创建响应模型类 SerializedName 然后使用 Gson 库将响应直接解析到模型类中,如下所示:-

    public class ResponseModel {
    
        @SerializedName("tblRegisteredUsers_UserName")
        private String userName;
    
        @SerializedName("tblRegisteredUsers_Password")
        private String password;
    
         public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
        }
    
    
    ResponseModel responseModel = new Gson().fromJson(response, ResponseModel.class);
    

    其中response将位于字符串中,您将派生类的responseModel对象,您可以从中访问来自后端的所有变量。