android - Retrofit-2 内容类型问题

标签 android retrofit retrofit2

我的 Api 接受 Content-Type application/json 作为 header 。 我按照 Retrofit Docs 中的说明完美地设置了 Header。

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

但是在请求日志中它正在返回 Content-Type txt/html。那么我应该如何解决这个问题?这个 api 在 POSTMAN 中运行良好 enter image description here

enter image description here

最佳答案

在 Retrofit 1.9 和 2.0 中尝试这种类型的 header 。对于 Json 内容类型。

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

您可以添加更多标题,即

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

动态添加到标题:

@POST("user/classes")
Call<ResponseModel> addToPlaylist(@Header("Content-Type") String content_type, @Body RequestModel req);

调用你的方法,即

mAPI.addToPlayList("application/json", playListParam);

或者

想每次都通过然后用http拦截器创建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());
            }
        });

然后添加到改造对象

Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();

UPDATE 如果您使用 Kotlin,请删除 { } 否则它将不起作用

关于android - Retrofit-2 内容类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35747524/

相关文章:

android - 改造更改一次 api 调用的读取超时

android - Telegram API 入门 : Any useful resource?

java - java的console.log()是什么?

android - 如何使 Sqlite 中的字段唯一?

json - Gson 或 Moshi : field in POJO could have 2 types, 如何保存到任何字段

java - com.google.gson.JsonSyntaxException : java. lang.IllegalStateException:预期为 BEGIN_OBJECT 但在第 1 行第 1 列路径 $

java - 如何获取 Retrofit POST 请求的响应

android - 如何设置tablerows元素的权重?

java - Retrofit 中 RSS 提要解析期间的 ValueRequiredException

java - 如何从android中的嵌套对象访问setter?