Search code examples
javaandroiderror-codeurlrequestrequest-queueing

How to get response code from synchronous RequestFuture request


I am using the strava API for an app. I am making synchronous requests as can be seen by the code below.

 try {
            RequestQueue queue = Volley.newRequestQueue(context);
            RequestFuture<String> future = RequestFuture.newFuture();
            StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future);
            queue.add(request);

            dataResponse = dealWithResponse(future.get()); 

        } catch (ExecutionException e) {
            System.err.println(e.getLocalizedMessage());
            System.err.println(e.getMessage());
            System.err.println(e.toString());
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }

I want to know how can I get the response code in the event of an error? for example some rides I request have been deleted / are private and i receive a 404 error code. Other times I have run out of API requests and get a code of 403. How can i differentiate between the thrown errors.

Thank you very much for your help!


Solution

  • Override parseNetworkError on your request:

    StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future) {
        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            if (volleyError != null && volloeyError.networkResponse != null) {
                int statusCode = volleyError.networkResponse.statusCode;
                switch (statusCode) {
                    case 403:
                        // Forbidden
                        break;
                    case 404:
                        // Page not found
                        break;
                }
            }
            return volleyError;
        }
    };