我需要創建一個OkHttp interceptor
,它讀取請求的Content-Type
頭的值(帶有正文的POST請求)。不幸的是,當我試圖通過request.headers
訪問它時,它不在那里(我可以看到其他自定義標頭,但看不到Content-Type
)。然而,我可以在HttpLoggingInterceptor
的日志中清楚地看到它。
我正在使用Retrofit
Sample code:
//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)
}
}
interceptor:
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
中不可見
我做錯了什么?
查看RequestBody,它包含這些信息。