Okhttp3: 在所有请求中添加全局头错误

问题描述 投票:1回答:1

我想为我所有的请求定义一个全局的头,我使用的是okhttp3。我使用的是okhttp3.我在论坛上搜索了一下,发现了一个方法,我尝试着去实现。

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

然而,我在执行过程中得到一个错误,我认为这与拦截器有关。异常情况如下。

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)

有谁知道我的错误在哪里,能帮帮我吗?最好先谢谢你!

java okhttp interceptor
1个回答
2
投票

根据文档httpClient.networkInterceptors()

返回一个观察单个网络请求和响应的不可改变的拦截器列表。

由于它是一个不可改变的列表,你不能向它添加元素,即一个 java.lang.UnsupportedOperationException 被抛在 networkInterceptors().add(...)

EDIT:

为了解决这个问题,请将 new OkHttpClient();

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


0
投票

你能不能试着只用拦截器而不用网络拦截器,因为网络拦截器有重定向和重试等特殊用途。

© www.soinside.com 2019 - 2024. All rights reserved.