1
嘗試添加一個攔截器來添加標頭到okhttp3和retrofit2的請求。我注意到頭文件沒有被添加到請求中,我的system.out.println調試行從未被調用。不知道爲什麼,但這裏是我的代碼:攔截器沒有被調用retrofit2
創建服務:
OkHttpClient client = new OkHttpClient();
client.newBuilder()
.addInterceptor(new ServiceInterceptor(context))
.authenticator(new MyAuthenticator(context))
.build();
service = (new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build())
.create(Service.class);
ServiceInterceptor:
public class ServiceInterceptor implements Interceptor {
private final Context context;
public ServiceInterceptor(Context context){
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
System.out.println("Interceptor");
if(request.header("No-Authentication") == null){
request = request.newBuilder()
.addHeader("User-Agent", "APP NAME")
.addHeader("Authorization", "bearer " + PreferenceManager.getDefaultSharedPreferences(context).getString("access_token", ""))
.build();
}
return chain.proceed(request);
}
}
的問題不完全是一部分,但我的認證是從來沒有被稱爲要麼...:
public class MyAuthenticator implements Authenticator {
private Context context;
public MyAuthenticator(Context context){
this.context = context;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
//blah blah refresh token here...
return null;
}
}
我有同樣的問題。我沒有把它分配給一個新的變量,所以所有的配置設置都丟失了。但是現在我已經將它分配給了一個變量了。 – toobsco42