问题描述
我的Api接受Content-Type application/json作为标头.我已按照Retrofit Docs中所述完美设置Header.
My Api is accepting Content-Type application/json as headers.I set Header perfectly as mentioned in Retrofit Docs.
@Headers("Content-Type: application/json")
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
但是在请求日志中,它正在返回Content-Type txt/html.那么我该如何解决此问题?此api在POSTMAN中可以正常工作
But in Request Log it is Returning Content-Type txt/html.So how i should fix this issue? This api works fine in POSTMAN
推荐答案
为Retrofit 1.9和2.0尝试使用此类型的标头.对于Json内容类型.
Try this type header for Retrofit 1.9 and 2.0. For Json Content Type.
@Headers({"Accept: application/json"})
@POST("user/classes")
Call<playlist> addToPlaylist(@Body PlaylistParm parm);
您可以添加更多标题,即
You can add many more headers i.e
@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 Interceptor创建HttpClient对象:
Want to pass everytime then Create HttpClient object with http Interceptor:
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();
更新(如果您使用的是Kotlin),请删除 {}
,否则它将不起作用
UPDATE if you are using Kotlin remove the { }
else it will not work
这篇关于Retrofit-2内容类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!