我需要创建一个
OkHttp interceptor
来读取请求的 Content-Type
标头的值(带有正文的 POST 请求)。不幸的是,当我尝试通过 request.headers
访问它时,它不在那里(我可以看到其他自定义标头,但看不到 Content-Type
)。然而,我可以在HttpLoggingInterceptor
的日志中清楚地看到它。
我正在使用
Retrofit
示例代码:
//versions:
//okHttp: 4.10.0
//retrofit: 2.9.0
interface API {
@Headers("secret: aaa", "aaa: AAA", "bbb: BBB", "Content-Type: application/json")
@POST("/post")
suspend fun echoPOST(@Body bodyData: BodyData): Response<String>
}
data class BodyData(val secret: String = "aaaa", val nonsecret: String = "bbb")
val httpClient = OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
)
.addInterceptor(MyInterceptor())
.build()
val testRetrofitClient = Retrofit.Builder()
.baseUrl("https://httpbin.org")
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build()
val api = testRetrofitClient.create(API::class.java)
suspend fun testRequestPOST() {
try {
val response = api.echoPOST(BodyData())
} catch (e: Exception) {
Timber.e(e)
}
}
拦截器:
class MyInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
val request = chain.request()
val response = chain.proceed(request)
Log.d("HTTP", "Content-Type: ${request.header("Content-Type")}")
Log.d("HTTP", "request headers: ${request.headers.joinToString { it.first }}")
return response
}
}
当调用被触发时,Logcat 显示:
// output from HttpLoggingInterceptor
--> POST https://httpbin.org/post
Content-Type: application/json; charset=UTF-8
Content-Length: 35
secret: aaa
bbb: bbb123
ccc: ccc123
{"nonsecret":"bbb","secret":"aaaa"}
// output from MyInterceptor
Content-Type: null
request headers: secret, bbb, ccc
因此
Content-Type
标头存在于请求中(由 HttpLoggingInterceptor
记录),但在 MyInterceptor
中不可见
我做错了什么?