【问题标题】:OkHttp response 204 with content-type json带有内容类型 json 的 OkHttp 响应 204
【发布时间】:2020-09-19 01:16:51
【问题描述】:

当我使用 okhttp3 ver 4.7.2 创建带有第三个 api 的 json 请求时,我会收到响应 204。但是当我使用 asyncHttpClient 创建相同的 json 请求时,我会收到正确的数据。

这是我使用 okhttp3 的代码:

        MediaType JSON =  MediaType.get("application/json");

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(interceptor).build();

        RequestBody body = RequestBody.create("{}", JSON);
        Request request = new Request.Builder()
                .url(URL).post(body).build();
        System.out.println("Start");
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response.body().string()); // null
        System.out.println(response.code()); // 204

这是我使用 asyncHttpClient 的代码:

        ListenableFuture<org.asynchttpclient.Response> whenResponse = client
                .preparePost(URL)
                .addHeader("Content-Type", "application/json").setBody("{}").execute();
        org.asynchttpclient.Response response = whenResponse.get();
        System.out.println(response.getResponseBody()); // Correct response body
        System.out.println(response.getStatusCode()); // 200

【问题讨论】:

    标签: okhttp


    【解决方案1】:

    okhttp发送的请求json内容类型为application/json; charset=utf-8,第三个 api 只允许 application/json。所以他们的回应是 204。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      相关资源
      最近更新 更多