Android volley to handle redirect

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

提交回复
热议问题