我有几个api调用的android应用。我注意到每个电话都有
ApiService中的@Headers("Content-Type: application/json")
注释,因此我决定删除注释并通过拦截器将标头添加到所有请求:
val headers = { chain: Interceptor.Chain ->
val request = chain.request().newBuilder()
.addHeader("Content-Type", "application/json")
.build()
chain.proceed(request)
}
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(headers)
.addInterceptor(logging)
.build()
val customGson = GsonBuilder()
.registerTypeAdapter(NameValuesList::class.java, NamesValuesListConverter())
.create()
val retrofit = Retrofit.Builder()
.baseUrl("http://www.$fullDomain")
.addConverterFactory(GsonConverterFactory.create(customGson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()
service = retrofit.create(ApiService::class.java)
但是该服务器在api调用后返回错误。
在日志中,我看到当我有明确的@Headers()
批注时:
D/OkHttp: Content-Type: application/json
然后将其替换为拦截器:
D/OkHttp: Content-Type: application/json; charset=UTF-8
我尝试将拦截器更改为该拦截器:
val headers = { chain: Interceptor.Chain ->
val request = chain.request().newBuilder()
.headers(Headers.of(mutableMapOf("Content-Type" to "test")))
.build()
chain.proceed(request)
}
但是我仍然在日志中看到这个:
D/OkHttp: Content-Type: application/json; charset=UTF-8
因此,我的拦截器似乎没有应用或被覆盖。如何解决?
UPD 。我找到了原因:当我添加GsonConverterFactory时,它会自动添加标头Content-Type: application/json; charset=UTF-8
。如果不实现自定义ConverterFactory,有什么方法可以避免它?
答案 0 :(得分:1)
如文档所述: “注意:标头不会互相覆盖。具有相同名称的所有标头将包含在请求中。”
答案 1 :(得分:0)
试试这个
chain.request().newBuilder().removeHeader("Content-Type") .headers(Headers.of(mutableMapOf("Content-Type" to "test"))) .build()