Android volley to handle redirect

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

    Like many others, I was simply confused about why Volley wasn't following redirects automatically. By looking at the source code I found that while Volley will set the redirect URL correctly on its own, it won't actually follow it unless the request's retry policy specifies to "retry" at least once. Inexplicably, the default retry policy sets maxNumRetries to 0. So the fix is to set a retry policy with 1 retry (10s timeout and 1x back-off copied from default):

    request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f))
    

    For reference, here is the source code:

    /**
     * Constructs a new retry policy.
     * @param initialTimeoutMs The initial timeout for the policy.
     * @param maxNumRetries The maximum number of retries.
     * @param backoffMultiplier Backoff multiplier for the policy.
     */
    public DefaultRetryPolicy(int initialTimeoutMs, int maxNumRetries, float backoffMultiplier) {
        mCurrentTimeoutMs = initialTimeoutMs;
        mMaxNumRetries = maxNumRetries;
        mBackoffMultiplier = backoffMultiplier;
    }
    

    Alternatively, you can create a custom implementation of RetryPolicy that only "retries" in the event of a 301 or 302.

    Hope this helps someone!

提交回复
热议问题