用OkHttp 2.2和拦截器改造1.9

时间:2015-01-10 19:33:18

标签: android retrofit square okhttp

我认为这些最新版本应该是兼容的。有这条推文; https://twitter.com/JakeWharton/status/553066921675857922和Retrofit 1.9的更改日志也提到了它。

然而,当我尝试这个时:

        OkHttpClient httpClient = new OkHttpClient();
        httpClient.interceptors().add(new TokenExpiredInterceptor());

        mRestAdapter = new RestAdapter.Builder()
                .setEndpoint(API_ENDPOINT)
                .setClient(httpClient)
                .setLogLevel(BuildConfig.DEBUG ?
                        RestAdapter.LogLevel.FULL :
                        RestAdapter.LogLevel.NONE)
                .setRequestInterceptor(new AuthorizationInterceptor())
                .build();

它仍然不起作用。 setClient方法抱怨不兼容的Client对象;

Error:(29, 21) error: no suitable method found for setClient(OkHttpClient)
method Builder.setClient(Client) is not applicable
(argument mismatch; OkHttpClient cannot be converted to Client)
method Builder.setClient(Provider) is not applicable
(argument mismatch; OkHttpClient cannot be converted to Provider)

我错过了什么?我也看到OkHttpClient没有实现Client接口。

我现在正在使用这种方法; https://medium.com/@nullthemall/execute-retrofit-requests-directly-on-okhttp-2-2-7e919d87b64e

我是否误解了更改日志? Maye Retrofit 1.9可以在类路径中使用OkHttpClient 2.2,但接口还没有适应?

1 个答案:

答案 0 :(得分:15)

您正在将OkHttpClient传递给接受RestAdapter.Builder实施的Client。如果OkHttpClient实施中没有使用,则Client仅与Retrofit无关。

您应该将OkHttpClient传递给实现OkClient

Client实例

.setClient(new OkClient(httpClient))

OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(new TokenExpiredInterceptor());

mRestAdapter = new RestAdapter.Builder()
        .setEndpoint(API_ENDPOINT)
        .setClient(new OkClient(httpClient))
        .setLogLevel(BuildConfig.DEBUG ?
                RestAdapter.LogLevel.FULL :
                RestAdapter.LogLevel.NONE)
        .setRequestInterceptor(new AuthorizationInterceptor())
        .build();