UFO ET IT

지원되지 않는 작업 : Android, Retrofit, OkHttp.

ufoet 2021. 1. 10. 17:48
반응형

지원되지 않는 작업 : Android, Retrofit, OkHttp. OkHttpClient에 인터셉터 추가


인터셉터를 사용하여 Android에서 Retrofit 2.0-beta3 및 OkHttpClient를 통해 토큰 기반 인증을 추가하려고합니다. 하지만 OkHttpClient에 인터셉터를 추가하면 UnsupportedOperationException이 발생합니다. 내 코드는 다음과 같습니다. In 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;
    }

그리고 나는 그것을 다음과 같이 사용합니다.

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() );
        }
    });
}

하지만이 오류가 발생합니다.

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)

그것은 modifiableCollection이 아니라는 새로운 인터셉터를 추가 할 때 오류가 발생하지만 interceptors () 함수에 대한 문서는 다음과 같이 말합니다. / **

   * 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).
   */

내가 도대체 ​​뭘 잘못하고있는 겁니까? 버그일까요?


이 문제는 Retrofit 2.0-beta2Retrofit 2.0-beta3변경할 때 발생합니다 . OkHttpClient객체 를 생성하려면 빌더를 사용해야 합니다.

변경 :

 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);
        }
 });

받는 사람 :

 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();

문제가 해결 될 것입니다.


다른 답변이 작동하지 않으면 이것을 시도하십시오.

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new MyInterceptor())
    .build();
retrofit = new Retrofit.Builder()
    .baseUrl("http://google.com")
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();

ReferenceURL : https://stackoverflow.com/questions/34674820/unsupported-operation-android-retrofit-okhttp-adding-interceptor-in-okhttpcl

반응형