【问题标题】:Struggling with OkHttp interceptors与 OkHttp 拦截器作斗争
【发布时间】: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();

【问题讨论】:

标签: java json okhttp


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 2019-12-28
    相关资源
    最近更新 更多