【问题标题】:Okhttp3: Need help to use HeaderInterceptorOkhttp3:使用 HeaderInterceptor 需要帮助
【发布时间】: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


    【解决方案1】:

    您创建的拦截器类似乎没有实现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 请求正文为空。

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

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

    查看 OkHttp documentation 了解更多信息。

    【讨论】:

    • 非常感谢您的回答。我现在已经按照您的建议实施了它。但现在我有以下错误: - HeaderInterceptor 类型的方法intercept(Interceptor.Chain) 必须覆盖超类方法 - 实现 okhttp3.Interceptor.intercept 似乎我需要导入 okhttp3.interceptor.intercept... 但是导入 okhttp3.拦截器。拦截;不起作用...我该如何导入它?我以为“导入okhttp3.interceptor;”已经足够了,但显然还不够。
    • 我在项目中使用了 Java 1.5。在我将它更新到 1.6 后,它可以工作了......
    【解决方案2】:

    你检查过这个问题吗:Okhttp3: Add global header to all requests error

    应该是这样的 .addInterceptor(new Interceptor())

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多