Android volley to handle redirect

前端 未结 8 1262
名媛妹妹
名媛妹妹 2020-11-27 18:43

I recently started to use Volley lib from Google for my network requests. One of my requests get error 301 for redirect, so my question is that can volley handle redirect so

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 19:33

    If you dont want to modify the Volley lib you can catch the 301 and manually re-send the request.

    In your GsonRequest class implement deliverError and create a new Request object with the new Location url from the header and insert that to the request queue.

    Something like this:

    @Override
    public void deliverError(final VolleyError error) {
        Log.d(TAG, "deliverError");
    
        final int status = error.networkResponse.statusCode;
        // Handle 30x 
        if(HttpURLConnection.HTTP_MOVED_PERM == status || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_SEE_OTHER) {
            final String location = error.networkResponse.headers.get("Location");
            Log.d(TAG, "Location: " + location);
            final GsonRequest request = new GsonRequest(method, location, jsonRequest, this.requestContentType, this.clazz, this.ttl, this.listener, this.errorListener);
            // Construct a request clone and change the url to redirect location.
            RequestManager.getRequestQueue().add(request);
        }
    }
    

    This way you can keep updating Volley and not have to worry about things breaking.

提交回复
热议问题