我正在尝试使用 Retrofit (2.0.0-beta3),但是当使用身份验证器添加令牌时,我似乎无法从同步调用中获取数据。我们在后端的日志记录只显示了很多登录尝试,但我无法从正文中获取数据来实际添加到标头中。
public static class TokenAuthenticator implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// Refresh your access_token using a synchronous api request
UserService userService = createService(UserService.class);
Call<Session> call = userService.emailLogin(new Credentials("handle", "pass"));
// This call is made correctly, as it shows up on the back-end.
Session body = call.execute().body();
// This line is never hit.
Logger.d("Session token: " + body.token);
// Add new header to rejected request and retry it
return response.request().newBuilder()
.header("Auth-Token", body.token)
.build();
}
}
我不太确定为什么它甚至不打印任何东西。任何有关如何解决此问题的提示将不胜感激,感谢您花时间提供帮助。
这些是我一直在阅读的有关如何实施 Retrofit 的资料。
使用身份验证器:
使用 Retrofit 2 进行同步调用:
- https://futurestud.io/blog/retrofit-synchronous-and-asynchronous-requests
我设法使用 TokenAuthenticator 和拦截器获得了一个不错的解决方案,并认为我会分享这个想法,因为它可能会帮助其他人。
添加“TokenInterceptor”类来处理将令牌添加到标头的情况是令牌存在,而“TokenAuthenticator”类则处理不存在令牌的情况,我们需要生成一个令牌。
我确信有一些更好的方法来实现这一点,但我认为这是一个很好的起点。
public static class TokenAuthenticator implements Authenticator {
@Override
public Request authenticate( Route route, Response response) throws IOException {
...
Session body = call.execute().body();
Logger.d("Session token: " + body.token);
// Storing the token somewhere.
session.token = body.token;
...
}
private static class TokenInterceptor implements Interceptor {
@Override
public Response intercept( Chain chain ) throws IOException {
Request originalRequest = chain.request();
// Nothing to add to intercepted request if:
// a) Authorization value is empty because user is not logged in yet
// b) There is already a header with updated Authorization value
if (authorizationTokenIsEmpty() || alreadyHasAuthorizationHeader(originalRequest)) {
return chain.proceed(originalRequest);
}
// Add authorization header with updated authorization value to intercepted request
Request authorisedRequest = originalRequest.newBuilder()
.header("Auth-Token", session.token )
.build();
return chain.proceed(authorisedRequest);
}
}
Source:
http://lgvalle.xyz/2015/07/27/okhttp-authentication/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)