10

Every time I try to use POST method with Volley, I get sever error. I get null value in getCause, and some default value in getNetworkResponse.toString().

If I use GET method, this works fine (I get response from my url).

Can anybody help what can I do?

    Map<String, String> jsonParams = new HashMap<String, String>();
    jsonParams.put("teststr", "abd");

    RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
    JsonObjectRequest request = new JsonObjectRequest(
            Request.Method.POST,
            url,
            new JSONObject(jsonParams),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        Toast.makeText(getApplicationContext(), "Success"+response.toString(), Toast.LENGTH_LONG).show();
                    }catch(Exception e){
                        Toast.makeText(getApplicationContext(), "JSON ERROR", Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("abd", "Error: " + error
                                    + ">>" + error.networkResponse.statusCode
                                    + ">>" + error.networkResponse.data
                                    + ">>" + error.getCause()
                                    + ">>" + error.getMessage());
                }
            }) {

                @Override
                protected Map<String,String> getParams() {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("key", "value");
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
    };
    requestQueue.add(request);

Error Log:

Error: Error: com.android.volley.ServerError>>404>>[B@42b1e0d0>>null>>null

UPDATE: networkResponse.statusCode comes as 404, though the url is accessible (and return data if I just use GET method). If I remove header part in POST method, still the same.

the url:

<?php
    $response = array();

    $jsonString = file_get_contents('php://input');
    $jsonObj = json_decode($jsonString, true);

    if(!isset($jsonObj['teststr'])){
        $response["msg"] = "No data.";
    }else{
        $response["msg"] = "Success: ".$jsonObj['teststr'];
    }
    echo json_encode($response);
?>
abdfahim
  • 2,523
  • 10
  • 35
  • 71

8 Answers8

8

problem is your Queue. change your volley code to this:

 RequestQueue queue = Volley.newRequestQueue(this);
 String URL = EndPoints.BASE_URL + "/call";
 StringRequest request = new StringRequest(Request.Method.POST, URL,
  new Response.Listener<String>()
  {
    @Override
    public void onResponse(String response) {

      Log.d("onResponse", response);

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

      NetworkResponse response = error.networkResponse;
      String errorMsg = "";
      if(response != null && response.data != null){
        String errorString = new String(response.data);
        Log.i("log error", errorString);
      }
    }
  }
) {
  @Override
  protected Map<String, String> getParams()
  {

    Map<String, String> params = new HashMap<String, String>();
    params.put("key_1","value_1");
    params.put("key_2", "value_2");
    Log.i("sending ", params.toString());

    return params;
  }

};


 // Add the realibility on the connection.
 request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));

  // Start the request immediately
    queue.add(request);  

and your php (laravel) code to this:

    $response['success'] = true;
    $response['user']['tell'] = $user->tell;
    $response['user']['code'] = $user->code;
    $response['user']['time'] = $time;
    $response['user']['register_state'] = '1'
    return response()->json($response, 200);
hadi.ghasemian
  • 159
  • 1
  • 2
  • 7
  • // Add the realibility on the connection. request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f)); this line works like a charm . Thank you for great answer – Muhammad Ashfaq Nov 12 '19 at 08:26
  • Could you please provide more info about this? This mysteriously fixed all my issues. The POST requests were being made correctly and the backend was receiving them but a third party API I have no access to was failing. – AliAvci Apr 28 '22 at 16:06
6

First, try to make sure your server works well. You can use Postman(chrome plug-in) or any other way to send a post request to the url and see what it responses.

After make sure there's no problem with your server, let us solve the problem with volley.

There's some problem with JsonObjectRequest when you use POST method. like this Volley JsonObjectRequest Post request not working.

I suggest you use StringRequest first and overwrite the getParams method like you did before. After you survive this task, you can try to write your own request, not very difficult but very useful.

I also suggest add request.setShouldCache(false) before requestQueue.add(request);. By default, volley saves the response in its cache and this behavior may cause some strange problem.

Community
  • 1
  • 1
Kay Wu
  • 759
  • 6
  • 9
  • thanks, I'll try that .. Btw, I just found out that if I replace the PHP file with one simple text file containing JSON data (xxx.json), the same code works well. Does that mean anything special? – abdfahim May 14 '15 at 03:11
  • btw, POST is working if I just test with a simple HTML form and try to get $_POST variable on submit. – abdfahim May 14 '15 at 03:16
  • What I know about the JsonObjectRequest is that it works well with GET method, but when you use POST method, getParams simply not called. So I try to write my own request to solve this. – Kay Wu May 14 '15 at 03:21
  • well, I am not concern about get params .. I just need to send the JSONObject and get a response .... but it is just showing 404 error which means it can't find the page ... – abdfahim May 14 '15 at 03:23
  • Can you give the url for me to test? And what do you mean by send the JSONObject? What the volley does is sending your request with params to your server, your server answers with response, which is simple String. And then volley try to convert the String into JSONObject. – Kay Wu May 14 '15 at 03:28
  • Actually I am trying to send a JSONObject to server via line new JSONObject(jsonParams) as the 3rd parameter of the JsonObjectRequest. I Tried to do that using GET method as well, AND IT IS WORKING. But I am not sure whether I should send data using GET method as the jsonParams might be a very large array. – abdfahim May 14 '15 at 03:31
  • If you replace the PHP file with one simple text file containing JSON data (xxx.json), then GET method would work this way. The problem with JsonObjectRequest is that when you use POST method, the getParams simply didn't called, it acts like GET method. So it works in this place. – Kay Wu May 14 '15 at 03:35
  • okay .. let me try with GET method ... I could get the response, but had difficulties on the serverside to read the JSON volley is sending (in 3rd parameter). – abdfahim May 14 '15 at 03:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/77768/discussion-between-kay-wu-and-abd-fahim). – Kay Wu May 14 '15 at 03:41
  • @KayWu I get the same error(used String Request) but working in POSTMAN. Is there any problem with Server?? any help to find it in server – iSrinivasan27 Dec 12 '16 at 07:18
0

Well,I think you can first print the responseCode in your logcat

shoxive
  • 1
  • 1
  • thanks ... Just updated my post .. networkResponse.statusCode = 404 ... seems like my php file has some structural issue (the url is valid for sure) – abdfahim May 14 '15 at 02:39
0

Add this code before add to queue

request.setRetryPolicy(new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

sometimes, request is timeout before your php executed completely. so try this code. maybe can help

Bamz3r
  • 177
  • 2
  • 7
0

maybe it's related to your operator...

I have the same issue sending JasonObject with Volley.

I tested my app on 9-10 devices with two different operators.

The request on one operator returns an Error with everything null or blank data in it, on the other one everything works fine and I get my Response from API successfully.

I have no idea what do operators do that causes this problem... Maybe they use some kind of firewall that blocks sending JsonObject.

S.Aslpour
  • 86
  • 1
  • 1
  • 10
0

I tried to display the response as a String and the error went off.

Use response.toString() wherever you want to display the error or use it.

Sonu Sourav
  • 2,926
  • 2
  • 12
  • 25
0

In my case, the answer is retry policy setting. I put 30 seconds the timeout value, it should be 30000, not 30.

-1

try to increase timeout. i had the same issue and the request timeout was the problem.

Paulius Nyoumi
  • 191
  • 1
  • 12