【发布时间】:2020-08-25 08:06:42
【问题描述】:
我想为我的所有请求定义一个全局标头。我正在使用 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)
有谁知道我的错误是什么并可以帮助我吗?提前致谢!
【问题讨论】:
-
第 25 行?
-
第 25 行是 httpClient.networkInterceptors().add(new Interceptor()
-
请阅读我关于失败原因的回答。
标签: java okhttp interceptor