本文介绍了Okhttp3:将全局标头添加到所有请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为所有请求定义一个全局标头.我正在使用okhttp3.我在论坛上搜索了一下,然后找到了一种尝试实施的方法:

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!

推荐答案

根据文档httpClient.networkInterceptors()

由于这是一个不可变的列表,因此您不能向其中添加元素,即,在networkInterceptors().add(...)上抛出java.lang.UnsupportedOperationException

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

为解决此问题,请替换new OkHttpClient();

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

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

这篇关于Okhttp3:将全局标头添加到所有请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:44