get response when i call the post method

ahmed jallad

i want to be able to deal with response i'm receiving when i call the post method, i tested the post method in postman and it works fine and returns the following:

 [
{
    "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
    }
}

] other wise i get this response as follows if the login info is inncorect:

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

] i want to be able to check if the login in is success the users signs in and all his info stored in variables, here is my android code:

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


        }
    });

    }  

what i get in the response is a string with all the information, and i always get to failed to login. it treats the response as one string. a lot of posts talk about jsonarrayrequest but i don't know how to implement it in my case

Rudrik Patel

Create Response model class with variable and it's SerializedName then use Gson library to parse your response directly into model class like the following :-

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

Where response will be in the String and you will derive responseModel object of the class from which you can access all the variable that is coming from back-end.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why is __get called instead of __call when I call a nonexistent method?

Not having a response when I call my web service GET request

how to get response on http post method when post html data in ios?

Not able to post JSON Data to MVC Action Method using $.AJAX but I get a Post 200 OK Response

Get Response Header data from Post Call

Firestore returns me null value when I call the get method?

Why I am getting array JSON response when I call method from Web API?

is IEnumerable enumerated on call of the method or when enumerating the response

Unable to get the response in POST method in Python

How do I properly issue response to post when waiting for async method to complete?

How do I Mock a method that makes multiple POST and GET request all requiring different response data?

I override an property's setter in subclass,but when I call it at superclass's init method, why the subclass's method response?

Razor page I lost the User data Passed from the user page when I call it from the post method

How to check if the ajax call method is POST or GET?

why does Microsoft edge send empty http-referer on call of POST/REDIRECT/GET method if uri of request and response is same?

I get UNAUTHENTICATED error when I call Method: purchases.subscriptions.get endpoint

How to call JsonArrayRequest(response is an object array) for POST Method with a jsonobject body

I get success as the JSON response when I use DELETE method even though the id does not exist

getting get method when running post method

XMLHttpRequest POST redirects before I get the response

when call router.post method from url get error 404 not found in express.js

When using RestSharp, I am getting MethodNotFound on a POST but the response thinks its a GET?

I get this error when I insert a new post in the db "Call to a member function load() on null"

Why do I get parent elements when I call the SimpleXMLElement::xpath method on a child element?

How to get the response of a post api call then show error on the page

How to get response from unirest nodejs POST call?

Why I get null when I make post JSON to web API method?

Django : trying to call the get method after the post method for a class view

response of the post method is empty