如何在Retrofit 2.0中使用拦截器添加标题?


96

我们的团队决定采用Retrofit 2.0,而我正在对此进行一些初步研究。我是这个图书馆的新手。

我想知道如何interceptor通过Android应用程序中的Retrofits 2.0添加自定义标题。有很多关于在Retrofit 1.X中使用添加标头的教程interceptor,但是由于API在最新版本中发生了很大变化,因此我不确定如何在新版本中适应这些方法。另外,Retrofit尚未更新其新文档。

例如,在以下代码中,应如何实现Interceptor该类以添加额外的标头?此外,未记录的Chain对象到底是什么?何时会intercept()被调用?

    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            // How to add extra headers?

            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_API_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

1
确保您的BASE_API_URL结尾于/并且API网址不(stuff/post/whatever
EpicPandaForce 2015年

Answers:


120

看一下这个。

public class HeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader("appid", "hello")
                .addHeader("deviceplatform", "android")
                .removeHeader("User-Agent")
                .addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
                .build();
        Response response = chain.proceed(request);
        return response;
    }
}

科特林

class HeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response = chain.run {
        proceed(
            request()
                .newBuilder()
                .addHeader("appid", "hello")
                .addHeader("deviceplatform", "android")
                .removeHeader("User-Agent")
                .addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
                .build()
        )        
    }
}

谢谢!!那么,这intercept()是在每次从应用程序发送请求时触发的吗?我们可以捕获中间响应以进行重定向,还是仅获得最终响应?
hackjutsu,2015年

每个请求都调用此函数,如果我知道正确的话,这是因为您将其添加为拦截器,而不是网络拦截器。我认为您只能在这里得到最终的响应,但是可能会有一个配置允许将重定向视为我不知道的重定向(也有一个用于HTTP URL连接的
重定向

1
只是参考此链接:github.com/square/okhttp/wiki/Interceptors,并获得信息,我需要:)谢谢〜
hackjutsu

5
仅供参考,您需要使用构建器代替client.interceptors()。看起来像new OkHttpClient.Builder().addInterceptor(<Your Interceptor>).build()
GLee

22

可接受答案的另一种选择

public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        request = request.newBuilder()
                .addHeader("headerKey0", "HeaderVal0")
                .addHeader("headerKey0", "HeaderVal0--NotReplaced/NorUpdated") //new header added
                .build();

        //alternative
        Headers moreHeaders = request.headers().newBuilder()
                .add("headerKey1", "HeaderVal1")
                .add("headerKey2", "HeaderVal2")
                .set("headerKey2", "HeaderVal2--UpdatedHere") // existing header UPDATED if available, else added.
                .add("headerKey3", "HeaderKey3")
                .add("headerLine4 : headerLine4Val") //line with `:`, spaces doesn't matter.
                .removeAll("headerKey3") //Oops, remove this.
                .build();

        request = request.newBuilder().headers(moreHeaders).build();

        /* ##### List of headers ##### */
        // headerKey0: HeaderVal0
        // headerKey0: HeaderVal0--NotReplaced/NorUpdated
        // headerKey1: HeaderVal1
        // headerKey2: HeaderVal2--UpdatedHere
        // headerLine4: headerLine4Val

        Response response = chain.proceed(request);
        return response;
    }
}

真好!那么request.newBuilder().headers(moreHeaders).build()将保留原始标题吗?
hackjutsu

1
是。除非调用removeAll(String name),否则不会从请求中删除任何标头。
VenomVendor 2015年

@VenomVendor请在这里帮助我解决类似的问题stackoverflow.com/questions/45078720 / ... 谢谢
user606669

不会继续创建新对象吗?
TheRealChx101 '19

3
   public class ServiceFactory {  
    public static ApiClient createService(String authToken, String userName, String password) {
            OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(
                            chain -> {
                                Request request = chain.request().newBuilder()
                                        .headers(getJsonHeader(authToken))
                                        .build();
                                return chain.proceed(request);
                            })
                    .authenticator(getBasicAuthenticator(userName, password))
                    .build();
            return getService(defaultHttpClient);
        }
        private static Headers getJsonHeader(String authToken) {
            Headers.Builder builder = new Headers.Builder();
            builder.add("Content-Type", "application/json");
            builder.add("Accept", "application/json");
            if (authToken != null && !authToken.isEmpty()) {
                builder.add("X-MY-Auth", authToken);
            }
            return builder.build();
        }
        private static Authenticator getBasicAuthenticator(final String userName, final String password) {
            return (route, response) -> {
                String credential = Credentials.basic(userName, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            };
        }
          private static ApiClient getService(OkHttpClient defaultHttpClient) {
            return new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(defaultHttpClient)
                    .build()
                    .create(ApiClient.class);
        }
}

2

您可以使用拦截器及其类似的内置方法进行标头

   interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder builder = original.newBuilder();

            builder.header("Authorization","Bearer "+ LeafPreference.getInstance(context).getString(LeafPreference.TOKEN));

            Request request = builder.method(original.method(), original.body())
                    .build();
            Log.e("request",request.urlString());
            Log.e("header",request.header("Authorization"));
            return chain.proceed(request);
        }
    });
}

我想知道您在这个地方如何获得背景信息
rupinderjeet

@rupinderjeet可能是final Context context参数列表中的a 。
TheRealChx101 '19

@ TheRealChx101只是要指出,我们不应该context在这里,因为这是业务逻辑。
rupinderjeet
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.