Volley Server Error with null Network response
Asked Answered
S

8

11

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);
?>
Saphena answered 14/5, 2015 at 1:29 Comment(3)
Have you checked error.getMessage(); ?Violet
Yup, that is null as wellSaphena
have you got a solution, am lost with the same error and the server is responding normally when tested with postmanDichotomy
H
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);
Hufuf answered 9/9, 2018 at 7:48 Comment(2)
// Add the realibility on the connection. request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f)); this line works like a charm . Thank you for great answerSyconium
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.Doublestop
U
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.

Unfrequented answered 14/5, 2015 at 3:7 Comment(10)
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?Saphena
btw, POST is working if I just test with a simple HTML form and try to get $_POST variable on submit.Saphena
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.Unfrequented
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 ...Saphena
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.Unfrequented
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.Saphena
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.Unfrequented
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).Saphena
Let us continue this discussion in chat.Unfrequented
@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 serverKindness
A
0

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

Abeyta answered 14/5, 2015 at 2:37 Comment(1)
thanks ... Just updated my post .. networkResponse.statusCode = 404 ... seems like my php file has some structural issue (the url is valid for sure)Saphena
K
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

Katonah answered 3/4, 2016 at 6:19 Comment(0)
G
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.

Gateway answered 2/2, 2017 at 10:44 Comment(0)
O
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.

Operculum answered 8/7, 2019 at 6:50 Comment(0)
P
0

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

Pergola answered 2/6, 2020 at 9:42 Comment(0)
P
-1

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

Phyliciaphylis answered 21/1, 2021 at 10:44 Comment(1)
That's the same solution as in Kenneth's answer.Eiser

© 2022 - 2024 — McMap. All rights reserved.