如何从响应中获取自定义标头(retrofit和rxjava)

时间:2019-10-24 07:17:31

标签: swift retrofit rx-java

我正在尝试从代码中的所有REST API响应中获取一些自定义HTTP标头。 这是我启动客户端的方法:

private fun initializeClient(): OkHttpClient {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val httpClient = OkHttpClient.Builder()
                .addInterceptor(object : Interceptor {
                    override fun intercept(chain: Interceptor.Chain): Response {
                        val original = chain.request()

                        val request = original.newBuilder()
                                .header("Content-Type", "application/json")
                                .method(original.method, original.body)
                                .build()

                        return chain.proceed(request)
                    }

                })
                .addInterceptor(interceptor)
                .build()
        return httpClient
    }

private fun initializeApi() {
        api = Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(initializeClient())
                .build()
                .create(RestApi::class.java)
    }

以下是改造实施的示例:

@POST("/register")
    fun registerUser(@Body registerPostData: RegistrationForm): Single<RegistrationResponse>

和ViewModel部分:

disposable.add(
                api.registerUser(form)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(object : DisposableSingleObserver<Member>() {
                            override fun onSuccess(value: RegistrationResponse?) {
// no headers in here
                                response.value = value
                            }

                            override fun onError(e: Throwable?) {

                            }

                        })
        )

服务器在所有API响应中返回一些x-custom-header,我需要在所有调用中捕获它们。

谢谢!

1 个答案:

答案 0 :(得分:0)

更改您的改装类以返回Response

@POST("/register")
fun registerUser(@Body registerPostData: RegistrationForm): Single<Response<RegistrationResponse>>

然后:

override fun onSuccess(result: Response<RegistrationResponse>?) {
    // get header from response.headers()
}