Alaa AbuZarifa
Alaa AbuZarifa

Reputation: 1249

Volley Post request returns no response inside onResponse

So I wanna print the result of the response and then generates data for the models using gson, but the response never gets return yet onResponse is called.!

if you notice Logcat, the log.i inside onResponse isn't showing..!? but inside the onSuccess of the Activity that uses this request, it shows logs normally, but if the log contains the response object it does not show which very weird and doesn't make any sense..!?

Logcat

I/getUrl:: http://1925.232.55/login.php
I/getParams:: {username =samy, password=123456}
D/libc: [NET] android_getaddrinfofornetcontext+,hn 20(0x6),sn(),hints(known),family 0,flags 1024, proc=com...
D/libc: [NET] android_getaddrinfo_proxy get netid:0
D/libc: [NET] android_getaddrinfo_proxy-, success
I/onSuccess:: check /* this log inside the Activity which uses this request */

I tried test the request using PostMan with the same url and params and it returns json response normally..?

Postman response

{
    "status": "success",
    "user_id": "10",
    "user_name": "samy",
    "full_name": "samy samy",
    "picture": "st_pictures/IMG_085207.jpg",
    "level": "1",
    "school": "NY School",
    "city": "NY",
    "class": "6",
    "age": "22",
    "teacher": "2",
    "token": "f808e758sdfsdfsf162dbdfcf88e3dc8a96"
}

The request code

 final RequestQueue queue = Volley.newRequestQueue(context);

      final StringRequest sr = new StringRequest(Request.Method.POST, getLoginURL(), new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
          Log.i("onResponse: ", response + "");
      requestResult.onSuccess(response);


      }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
      requestResult.onFail(error);

           VolleyLog.e("Error: ", error.getMessage());
          error.printStackTrace();
        }
      })
      {
        @Override
        protected Map<String, String> getParams() {
          Map<String, String> params = new HashMap<String, String>();
          params.put("username ", un);
          params.put("password", pass);
          Log.i( "getParams: ", params.toString());
          return params;
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
          Log.i( "getUrl: ",getUrl());
          return super.getBody();

        }
      }
      ;

      queue.add(sr);

UPDATE #1

URL http://clients.intertech.ps/raz/std.php

 E/Volley: [1] 2.onErrorResponse: Error: 
 W/System.err: com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of 
 W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:73)
 W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:123)
 W/System.err: Caused by: org.json.JSONException: End of input at character 0 of 
 W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
 W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
 W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
 W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:68)
 W/System.err:  ... 1 more

Upvotes: 2

Views: 1864

Answers (3)

Felipe Gonz&#225;lez
Felipe Gonz&#225;lez

Reputation: 86

This question was asked a long time ago but I had the same problem, after hours I got it to work with Volley

Used StringRequest instead of JsonObjectRequest, for any reason i got to much problems with JOR and I used the getHeaders function of @Oussema Aroua

final Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("RESPONSE", String.valueOf(response));
        }
    };

final Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            //Handle your errors
        }
    };

StringRequest request = new StringRequest(Request.Method.POST, url,
            responseListener, errorListener) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            //Put your params for post
            return params;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String,String> params = new HashMap<>();
            params.put("Content-Type","application/x-www-form-urlencoded"); //-> this is the key
            return params;
        }
    };

.. and you will get the json response from the server in onResponse

Upvotes: 2

Oussema Aroua
Oussema Aroua

Reputation: 5339

it's not a StringRequest you need to use JsonObjectRequest be cause your response begin with the {

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                       requestResult.onSuccess(response);
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        requestResult.onFail(error);
                    }
                });

try to add under the getParams:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String,String> params = new HashMap<String, String>();
    params.put("Content-Type","application/x-www-form-urlencoded");
    return params;
}

[UPDATE] :

i have no idea why with volley is not working but i changes to ion link and it works :

Ion.with(this)
                .load("http://clients.intertech.ps/raz/std.php")
                .setBodyParameter("username", "layal")
                .setBodyParameter("password", "123456")
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject jsonObject) {
                        Log.e("TAG", "onCompleted: " + jsonObject.toString());
                    }
                });

Upvotes: 0

attakon
attakon

Reputation: 61

You have to use a JsonObjectRequest, like this :

HashMap<String, String> params = new HashMap<String, String>();
params.put("username","samy");
params.put("password","123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
 new Response.Listener<JSONObject>() {
       @Override
       public void onResponse(JSONObject response) {
           Gson gson = new Gson();
           YourClass yourClass = gson.fromJson(response.toString(), yourClass.class);
       }
   }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
            //error
       }
   });

Upvotes: 0

Related Questions