Android volley to handle redirect

前端 未结 8 1203
名媛妹妹
名媛妹妹 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:34

    End up doing a merge of what most @niko and @slott answered:

    // Request impl class
    // ...
    
        @Override
        public void deliverError(VolleyError error) {
            super.deliverError(error);
    
            Log.e(TAG, error.getMessage(), error);
    
            final int status = error.networkResponse.statusCode;
            // Handle 30x
            if (status == HttpURLConnection.HTTP_MOVED_PERM ||
                    status == HttpURLConnection.HTTP_MOVED_TEMP ||
                    status == HttpURLConnection.HTTP_SEE_OTHER) {
                final String location = error.networkResponse.headers.get("Location");
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Location: " + location);
                }
                // TODO: create new request with new location
                // TODO: enqueue new request
            }
        }
    
        @Override
        public String getUrl() {
            String url = super.getUrl();
    
            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                url = "http://" + url; // use http by default
            }
    
            return url;
        }
    

    It worked well overriding StringRequest methods.

    Hope it can help anyone.

    0 讨论(0)
  • 2020-11-27 19:41

    I fixed it catching the http status 301 or 302, reading redirect url and setting it to request then throwing expection which triggers retry.

    Edit: Here are the main keys in volley lib which i modified:

    • Added method public void setUrl(final String url) for class Request

    • In class BasicNetwork is added check for redirection after // Handle cache validation, if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || statusCode == HttpStatus.SC_MOVED_TEMPORARILY), there I read the redirect url with responseHeaders.get("location"), call setUrl with request object and throw error

    • Error get's catched and it calls attemptRetryOnException

    • You also need to have RetryPolicy set for the Request (see DefaultRetryPolicy for this)

    0 讨论(0)
提交回复
热议问题