Okhttp3:使用HeaderInterceptor需要帮助

问题描述 投票:0回答:2

我想为我的所有请求使用全局头。因此,我实现了以下类:

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 =新的OkHttpClient.Builder()。addInterceptor(?? MyInterceptor ??)。build();我尝试过这样的事情:addInterceptor(HeaderInterceptor.intercept()),但是这不起作用...

有人可以帮我吗?其余的看起来还不错吗?提前非常感谢!

java okhttp interceptor
2个回答
0
投票

您是否已检查过此问题:Okhttp3: Add global header to all requests error

应该是类似.addInterceptor(new Interceptor())


0
投票

您创建的拦截器类似乎未实现Interceptor接口。您需要执行以下操作

public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader("Accept", "application/json")
                .addHeader("Basic ", "abcdefghi123456789")
                .build();
        Response response = chain.proceed(request);
        return response;
    }  
}

请注意,您不应除非确实需要,否则将请求的方法和主体修改为.method("GET", null),因为它可能导致客户端发出的所有HTTP请求都将GET请求设为null”身体。

然后在按如下所示构建客户端时添加拦截器

    OkHttpClient httpClient = new OkHttpClient.Builder()
                 .addInterceptor(new HeaderInterceptor()).build();

有关更多信息,请查看OkHttp documentation。>

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