与 OkHttp 拦截器作斗争

Posted

技术标签:

【中文标题】与 OkHttp 拦截器作斗争【英文标题】:Struggling with OkHttp interceptors 【发布时间】:2021-09-01 14:05:57 【问题描述】:

我需要覆盖 OkHttp 默认设置的内容类型标头。我已经尝试了很多东西,这是我最接近它的工作。从我发现我需要使用拦截器但真的很难学习它们。我的预期行为是让我的 API POST 请求通过,但这不是因为没有正确设置内容类型并且我得到 415 Unsupported Media Type。我正在使用 ITGlue API。

public class APIHandler 
     public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    public class DefaultContentTypeInterceptor implements Interceptor 

        public Response intercept(Interceptor.Chain chain)
                throws IOException 

            Request originalRequest = chain.request();
            Request requestWithUserAgent = originalRequest
                    .newBuilder()
                    .header("Content-Type", "application/vnd.api+json")
                    .build();

            return chain.proceed(requestWithUserAgent);
        
    
    private final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new DefaultContentTypeInterceptor()).build();


    public void run(String input) throws Exception 
        RequestBody requestBody = RequestBody.Companion.create("\"data\": \n" +
                "  \"type\": \"attachments\",\n" +
                "  \"attributes\": \n" +
                "    \"attachment\": \n" +
                "      \"content\": \""+input+"\",\n" +
                "      \"file_name\": \"test.png\"\n" +
                "    \n" +
                "  \n" +
                "\n" +
                "", JSON);
        Request request = new Request.Builder()
                .url("https://api.itglue.com/configurations/33880577/relationships/attachments")

                .header("Content-Type", "application/vnd.api+json")
                .addHeader("x-api-key", "ITG.baaa9df19a1ec7d2c9159d2c18eef763.TG9j_uj3kiDHIjZ4TMPz_IrfIBh9jLDvdEKc9UiwGNmVz6jnyYwFqrDgiA4ZaJB9")
                .post(requestBody)
                .build();

        System.out.println(requestBody.toString());

        Response response = client.newCall(request).execute();

【问题讨论】:

您是否尝试过注册网络拦截器? square.github.io/okhttp/interceptors/#network-interceptors 【参考方案1】:

首先尝试使用正确的媒体类型创建您的RequestBody

        RequestBody requestBody = RequestBody.create("...", MediaType.get("application/vnd.api+json")));

【讨论】:

以上是关于与 OkHttp 拦截器作斗争的主要内容,如果未能解决你的问题,请参考以下文章

Android OkHttp3 :最简单&粗暴(使用与原理)讲解

OKHTTP拦截器CallServerInterceptor的简单分析

OkHttp3 拦截器源码分析

Okhttp 3.x 动态添加/删除验证器/拦截器

ConnectInterceptor 解析——OkHttp 源码详解

Okhttp拦截器问题