尝试使用这个类型的头信息来适用于Retrofit 1.9和2.0,用于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 retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
更新:如果您正在使用 Kotlin,请删除 { }
,否则它将无法正常工作。
enqueue
时,我看不到默认的头部。 - vipernew OkHttpClient.Builder()
替代new OkHttpClient()
。 - Wojtek