Okhttp3: Add global header to all requests error

旧巷老猫 提交于 2020-12-12 09:40:47

问题


I would like to define a global header for all my requests. I am using okhttp3. I searched here in the forum and found an approach, which I tried to implement:

public static void main(String[] args) throws Exception {
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.networkInterceptors().add(new Interceptor() {
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder()
                    .method("GET", null)
                    .addHeader("Accept", headerType)
                    .addHeader(headerAuthorization, headerAuthorizationValue)
                    .build();

            return chain.proceed(request);
        }
    });

    Request request = new Request.Builder()
            .url(Connection.BASE_URL)
            .build();

    okhttp3.Response response = httpClient.newCall(request).execute();
    String responseData = response.body().string();
    System.out.println(responseData);
}

However, I get an error during execution and I think it is related to the Interceptor. The exception is as follows:

Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1062)
at jira.Program.main(Program.java:25)

Does anyone see what my mistake is and can help me please? Best thanks in advance!


回答1:


According to the documentation httpClient.networkInterceptors()

Returns an immutable list of interceptors that observe a single network request and response.

Since it is an immutable list you can not add elements to it, i.e. an java.lang.UnsupportedOperationException is thrown on networkInterceptors().add(...)

EDIT:

In order to fix this, please replace new OkHttpClient();

with new OkHttpClient.Builder().addInterceptor(...).build().




回答2:


Can you please try to use just interceptor instead of network interceptor, because Network interceptors has special use like redirects and retries.



来源:https://stackoverflow.com/questions/61701646/okhttp3-add-global-header-to-all-requests-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!