java 不支持的操作:Android、Retrofit、OkHttp。在 OkHttpClient 中添加拦截器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34674820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unsupported operation: Android, Retrofit, OkHttp. Adding interceptor in OkHttpClient
提问by Usman khan
I am trying to add token based authentication via Retrofit 2.0-beta3 and OkHttpClient in Android using interceptors. But I get UnsupportedOperationException when I add my interceptor in OkHttpClient. Here is my code: In ApiClient.java
我正在尝试使用拦截器在 Android 中通过 Retrofit 2.0-beta3 和 OkHttpClient 添加基于令牌的身份验证。但是当我在 OkHttpClient 中添加我的拦截器时,我得到了 UnsupportedOperationException。这是我的代码:在 ApiClient.java 中
public static TrequantApiInterface getClient(final String token) {
if( sTreqantApiInterface == null) {
Log.v(RETROFIT_LOG, "Creating api client for the first time");
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
sTreqantApiInterface = client.create(TrequantApiInterface.class);
}
return sTreqantApiInterface;
}
And I use it like:
我像这样使用它:
private void ampFreqTest(){
String token = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE)
.getString(getString(R.string.key_token), "");
service = ApiClient.getClient(token);
//I get an exception on this line:
Call<List<AmpFreq>> call = service.getUserAmpFreq("1");
call.enqueue(new Callback<List<AmpFreq>>() {
@Override
public void onResponse(Response<List<AmpFreq>> response) {
Toast.makeText(HomeScreen.this, "Got result", Toast.LENGTH_LONG);
Log.v(ApiClient.RETROFIT_LOG, "Success api client." + response.message());
Log.v(ApiClient.RETROFIT_LOG, "Success api client.");
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(HomeScreen.this, t.getMessage() , Toast.LENGTH_LONG);
Log.v(ApiClient.RETROFIT_LOG, "Fail api client." + t.getMessage() );
}
});
}
But I get this error:
但我收到此错误:
Process: com.trequant.usman.trequant_android, PID: 14400
java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Collections.java:932)
at com.trequant.usman.trequant_android.api.ApiClient.getClient(ApiClient.java:41)
It gives me error on adding a new interceptor saying that it is not modifiableCollection but the documentation for interceptors() function says: /**
添加新的拦截器时出现错误,说它不是可修改的Collection,但拦截器()函数的文档说:/**
* Returns a modifiable list of interceptors that observe the full span of each call: from before
* the connection is established (if any) until after the response source is selected (either the
* origin server, cache, or both).
*/
What am I doing wrong? Could it be a bug?
我究竟做错了什么?这可能是一个错误吗?
回答by Konrad Krakowiak
This issue occurs when you change Retrofit 2.0-beta2to Retrofit 2.0-beta3. You have to use builder if you want to create OkHttpClient
object.
当您将Retrofit 2.0-beta2更改为 Retrofit 2.0-beta3时会出现此问题 。如果要创建OkHttpClient
对象,则必须使用 builder 。
Change :
改变 :
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
to :
到 :
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
It should resolve your problem.
它应该可以解决您的问题。
回答by Jimmy O. Rojas Medrano
Try this if the other answer doesn't work:
如果其他答案不起作用,请尝试此操作:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new MyInterceptor())
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://google.com")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
回答by Rahul Jain
You Can Add In this way also.
您也可以通过这种方式添加。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("ENDPOINT_URL")
.addConverterFactory(GsonConverterFactory.create()).client(client)
.build();