改造-2内容类型问题

Muh*_*raf 22 android retrofit retrofit2

我的Api正在接受Content-Type application/json作为标题.我按照Retrofit Docs中的说法完美地设置了Header.

@Headers("Content-Type: application/json")
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
Run Code Online (Sandbox Code Playgroud)

但在请求日志中它返回Content-Type txt/html.那么我应该如何解决这个问题呢?这个api在POSTMAN中运行良好 在此输入图像描述

在此输入图像描述

Pha*_*hai 21

你可以在我的解决方案中尝试一个:

@POST("user/classes")
Call<playlist> addToPlaylist(@Header("Content-Type") String content_type, @Body PlaylistParm parm);
Run Code Online (Sandbox Code Playgroud)

然后打电话

mAPI.addToPlayList("application/json", playListParam);
Run Code Online (Sandbox Code Playgroud)

要么

创建HttpClient对象

OkHttpClient httpClient = new OkHttpClient();
        httpClient.networkInterceptors().add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });
Run Code Online (Sandbox Code Playgroud)

然后添加到改装对象

Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
Run Code Online (Sandbox Code Playgroud)


Avi*_*rma 21

尝试使用Retrofit 1.9和2.0.对于Json内容类型.

@Headers({"Accept: application/json"})
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
Run Code Online (Sandbox Code Playgroud)

你可以添加更多,即

@Headers({
        "Accept: application/json",
        "User-Agent: Your-App-Name",
        "Cache-Control: max-age=640000"
    })
Run Code Online (Sandbox Code Playgroud)


小智 8

这是一个适用于改造2(v2.5)和okhttp3的解决方案。如果您将这些标头添加到多个请求中,则效果特别好

OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                requestBuilder.header("Accept", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });

 OkHttpClient httpClient = httpClientBuilder.build();
 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();
Run Code Online (Sandbox Code Playgroud)


小智 3

尝试:

@POST("user/classes")
Call<playlist> addToPlaylist(
@Header("Content-Type") String contentType,
@Body PlaylistParm parm);
Run Code Online (Sandbox Code Playgroud)