我关注此帖:http://inthecheesefactory.com/blog/retrofit-2.0/en
并尝试按如下方式添加拦截器:
package test.com.testretrofit2;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class InterceptorTest {
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// Do anything with response here
return response;
}
});
}
然而,在线
client.interceptors().add(new Interceptor() {
我收到错误
'interceptors' has private access in com.squareup.okhttp.OkHttpClient.
我正在使用
com.squareup.retrofit:retrofit:2.0.0-beta1
它正在拉入okhttp-2.5.0。我看过OkhttpClient.java,拦截器()是公开的。
我使用的是错误的Retrofit 2.0库还是版本?
答案 0 :(得分:2)
编辑(事情真相) -
您的代码需要在方法中,而不仅仅是在类中。
public class InterceptorTest {
void myTest() {
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// Do anything with response here
return response;
}
});
}
}
编辑(另一种可能性) -
如果在此代码之前的代码中有未终止的作用域,则可以看到此错误。例如,
new Thread(new Runnable() {
@Override
public void run() {
});
client.interceptors().add(new SigningInterceptor());
将显示您在IDE中指示的错误,但在编译时会产生更多错误。请注意,在此示例中,Runnable
未正确终止。缺少}
。检查以确保{}
符合预期。
原始选项 -
您的错误和您发布的代码不匹配。如果该函数具有私有访问权限,则应该收到错误消息 -
'interceptors()' has private access in com.squareup.okhttp.OkHttpClient.
注意()的。
在这种情况下,这很重要,因为OkHttpClient
有一个名为interceptors
的私有成员,但是公共interceptors()
方法。
可以预期您在此行中看到的错误 -
client.interceptors.add(new Interceptor() {
请注意interceptors
之后的遗失()。在您致电interceptors
的所有地方仔细检查您的代码,看看您是否错过了括号。