【发布时间】:2020-08-26 00:07:18
【问题描述】:
我想为我的所有请求使用全局标头。因此我实现了以下类:
public class HeaderInterceptor {
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Basic ", "abcdefghi123456789")
.build();
Response response = chain.proceed(request);
return response;
}
}
现在我想在 main() 方法中执行以下操作:
public static void main(String[] args) throws Exception {
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(MyInterceptor).build();
Request reqAllProjects = new Request.Builder()
.url("https://example.com/projects")
.build();
Response resAllProjects = httpClient.newCall(reqAllProjects).execute();
String responseData = resAllProjects.body().string();
System.out.println(responseData);
}
我现在不确定如何使用我的 HeaderInterceptor。我想我必须在这里输入,对吧? OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(??MyInterceptor??).build(); 我尝试过这样的事情: addInterceptor(HeaderInterceptor.intercept()) 但这不起作用...
有人可以帮帮我吗?其余的看起来还好吗?非常感谢!
【问题讨论】:
标签: java okhttp interceptor