android - Retrofit2(拦截器)+GoogleApiClient如何刷新token

标签 android retrofit2 access-token okhttp google-api-java-client

在每个请求中获得有效 IdToken 的最佳方式是什么?

我的第一个赌注是 okhttpclient 拦截器,它将 token 添加到每个请求。但我不知道如何在拦截器中获取有效 token 。

GoogleApiClient 的文档建议在每次请求之前调用 silentSignIn(GoogleApiClient) 以获取有效 token 。问题是我无法访问拦截器内当前连接的 googleapiclient。

最佳答案

我最近遇到了类似的问题,我找到了一个不是很漂亮但可行的解决方案。 您可以使用静态变量。

  public class SessionData {

        private static String sessionId;

    public static String getSessionId() {
        return sessionId;
    }

    public static void setSessionId(String sessionId) {
        SessionData.sessionId = sessionId;
    }
    }

然后您可以在从 Google SDK 获取 IdToken 后设置它(例如,在用户登录后)。

SessionData.setSessionId(yourCurrentToken);

在您声明 Retrofit.Builder 的类中,您应该使用以下导入(如您所说,okhttp 拦截器)。

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

类的内容应该如下所示。

public class RestClient implements Interceptor {

    public RestClient() {

        OkHttpClient httpClient = new OkHttpClient();
        // add your other interceptors …
        // add logging as last interceptor

        httpClient.interceptors().add(this);  // <-- this adds the header with the sessionId to every request

        Retrofit restAdapter = new Retrofit.Builder()
                .baseUrl(RestConstants.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();

        if (SessionData.getSessionId() != null) {
            Request newRequest = originalRequest.newBuilder()
                    .header("sessionId", SessionData.getSessionId())
                    .build();
            return chain.proceed(newRequest);
        }
        return chain.proceed(originalRequest);

    }
}

关于android - Retrofit2(拦截器)+GoogleApiClient如何刷新token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562114/

相关文章:

android - 谷歌服务 JSON 文件

android - 更改规则后无法写入 Firebase

android - 更新 gradle Android Studio 后链接引用失败

android - 如何在 Kotlin 中抛出 HttpException - 改造 2 - 单元测试

java - 在 Retrofit 调用后更改折叠工具栏标题

android - Android中LinkedIn的Oauth 2.0授权

android - 如何在android中获取访问 token paypal

php - 让用户将视频从我的站点服务器上传到他们的 youtube channel

android - 缺少 NativeScript ANDROID_HOME

android - 使用 Retrofit2 和 Kotlin : Unable to create call adapter 在正文中发布数据