How do you prevent Retrofit from automatically following a 302

前端 未结 5 1376
忘了有多久
忘了有多久 2021-02-18 23:43

I have an authentication call that i\'m trying to make using Retrofit on Android. The call returns a 302 to either a success or failure page. The original 302 response brings ba

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 00:27

    I know this is an old post, maybe it will still help for someone. I have a similar problem, my solution was to add a redirectStrategy (http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/RedirectStrategy.html) to httpClient:

    private static final RestAdapter REST_ADAPTER= new RestAdapter.Builder()
                .setEndpoint(HTTP_TEST_URL)
                .setClient(new ApacheClient(HttpClients.custom()
                    .setRedirectStrategy(new RedirectStrategy() {
                        @Override
                        public boolean isRedirected(HttpRequest request, HttpResponse response,
                            HttpContext context) throws ProtocolException {
                            return response.getStatusLine().getStatusCode() == 302;
                        }
    
                        @Override
                        public HttpUriRequest getRedirect(HttpRequest request,
                            HttpResponse response, HttpContext context)
                            throws ProtocolException {
    
                            //String cookieValue = response.getFirstHeader("Set-Cookie").getValue();
                            String location = response.getFirstHeader("location").getValue();
    
                            HttpUriRequest request_= new HttpGet(location);
                            return request_;
                        }}).build()))
                .build();
    

    With this I can get access to any (private) url. I think the cookie data added automatically. Maybe you should rewrite the getRedirect(), isRedirected() functions to pass your special needs.

提交回复
热议问题