如何防止改装自动跟随302 [英] How do you prevent Retrofit from automatically following a 302
问题描述
我正在尝试使用Android上的Retrofit进行身份验证.该呼叫将302返回到成功或失败页面.原始的302响应会带回用于维持成功身份验证所需的会话cookie,但是Retrofit会在我有机会使用该cookie之前自动将请求移交给重定向网址.
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 back a session cookie needed to maintain authentication on success, however Retrofit is automatically handing the request off to the redirect url before I get a chance to consume the cookie.
是否有一种方法可以防止遵循重定向?还是有办法在Retrofit上编写一个响应处理程序,该处理程序可以在进行第二次调用之前添加适当的标头?
Is there a way to prevent following the redirect? Or is there a way to write a response handler on Retrofit that can add the appropriate header before making the second call?
推荐答案
为防止重定向,您必须配置客户端,例如,使用OkHttp 2:
to prevent the redirect you have to configure your client, e.g with OkHttp 2:
private sendRequest() {
OkHttpClient client = new OkHttpClient();
client.setFollowRedirects(false);
connectAdapter = new RestAdapter.Builder()
.setClient(new OkClient(client))
.setEndpoint("http://yourendpoint")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
connectAdapter.create(YourRequest.class).sendMyRequest("login","password");
}
使用OKHTTP 3(您可以从@gropapa阅读此答案):
With OKHTTP 3 (you can read this answer from @gropapa):
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.followRedirects(false);
OkHttpClient httpClient = builder.build();
这篇关于如何防止改装自动跟随302的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!