【问题标题】:Android Retrofit 2.0 adding headers with interceptor doesn't workAndroid Retrofit 2.0 添加带有拦截器的标头不起作用
【发布时间】:2018-03-04 00:04:03
【问题描述】:

我有 OkHttp 客户端的 Singleton 匕首模块,我正在尝试使用 Interceptor 添加标头

@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache, final LocalData localData) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(logging);
    client.addNetworkInterceptor(new Interceptor() {
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("Hp-Application", "Android");
            Request request = requestBuilder.build();
            Response originalResponse = chain.proceed(request);
            try {
                if (originalResponse.code() == 200) {
                    localData.setLastUpdateTime(System.currentTimeMillis());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return originalResponse;
        }
    });
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.cache(cache);
    return client.build();
}

但是查看日志我看不到预期的标题。我也收到错误,因为如果没有必需的标头,特定调用将无法工作。

我还尝试使用不同的类将其添加到 addInterceptor()/addNetworkInterceptor()

 public class HeaderInterceptor
        implements Interceptor {
    @Override
    public Response intercept(Chain chain)
            throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .addHeader("Hp-Application", "Android")
                .build();
        return chain.proceed(request);
    }
}

但是这种方式对我也不起作用。

如何将此标头添加到只有一个实现的应用程序的每个调用中?

【问题讨论】:

    标签: android retrofit2 interceptor okhttp3


    【解决方案1】:

    添加拦截器的顺序很重要。您的日志拦截器首先运行,然后才运行添加标头的拦截器。

    为了获得最佳的日志记录体验,请将日志拦截器设置为您添加的最后一个。

    【讨论】:

    • 是否有任何文档或发行说明中提到了这一点,这会有所帮助,请尽可能更新
    • 这是一个非常重要的信息。顺序真的很重要。谢谢
    【解决方案2】:

    嘿@Igor 试试这个 sn-p 这可能会有所帮助

    public class RetrofitClient {
    
        private static String BASE_URL = "http://192.168.0.100/rest/main.php/";
        private static Retrofit retrofit = null;
    
        public static Retrofit getRetroftInstance() {
            if (retrofit == null) {
    
                OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
                httpClient.addNetworkInterceptor(new SessionRequestInterceptor());
                httpClient.addNetworkInterceptor(new ReceivedCookiesInterceptor());
    
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(httpClient.build())
                        .build();
            }
    
            return retrofit;
        }}
    
    public class ReceivedCookiesInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
    
            if (!originalResponse.headers("Set-Cookie").isEmpty()) {
                HashSet<String> cookies = new HashSet<>();
                for (String header : originalResponse.headers("Set-Cookie")) {
                    cookies.add(header);
                    if(header.startsWith("XSRF-TOKEN")) {
                        String newCookie[]=header.split(";");
                        System.out.println("newCookie Length: "+newCookie.length);
                        for(String ss:newCookie) {
                            if(ss.startsWith("XSRF-TOKEN")) {
                                System.out.println("Cookies ss: " + ss);
                                sharedPrefs.setToken(ss);
                            }
                        }
                    }
                }
            }
            return originalResponse;
        }
    }
    
    public class SessionRequestInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
    
            Request.Builder request = original.newBuilder();
    
            request.header("Cookie",ServiceSharedPrefs.getInstance().getToken()));
    
            request.method(original.method(), original.body());
    
            return chain.proceed(request.build());
        }
    
    }
    

    【讨论】:

      【解决方案3】:
      new OkHttpClient.Builder()
                  .addInterceptor(
                          new Interceptor() {
                              @Override
                              public Response intercept(Chain chain) throws IOException {
                                  Request original = chain.request();
      
      
      
                                  // Request customization: add request headers
                                  Request.Builder requestBuilder = original.newBuilder().
                                          header(AUTHENTICATION_HEADER, AUTHENTICATION_KEY).
                                          method(original.method(), original.body());
      
      
                                  Request request = requestBuilder.build();
      
                                  //System.out.println(request.toString());
      
                                  return chain.proceed(request);
                              }
                          }).addInterceptor(logging)
                  .build();
      

      【讨论】:

        猜你喜欢
        • 2016-01-02
        • 2021-09-13
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 2019-12-07
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多