我的 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 中运行良好
最佳答案
在 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/