Retrofit2添加Header方式

一、注解静态添加方式

    @Headers({"Content_Type:application/json", "charset:UTF-8"})
    @POST("/config/getvalue")
    fun getConfig(@Body req: ConfigReq): Observable>

二、注解动态添加方式

@POST("order/carry")
fun takeOrder(
         @Header("groupID") groupID: String,
         @Body req: OperateOrderReq
    ): Observable>

三、通用拦截器方式

//创建拦截器
val interceptor = Interceptor { chain ->
    val request = chain.request()
    val requestBuilder = request.newBuilder()
    val url = request.url()
    val builder = url.newBuilder()
    requestBuilder.url(builder.build())
        .method(request.method(), request.body())
        .addHeader("Content_Type", "application/json")
        .addHeader("charset", "UTF-8")
         chain.proceed(requestBuilder.build())
}
//创建OKhttp
val client = OkHttpClient.Builder()
		.addInterceptor(interceptor)
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .retryOnConnectionFailure(false)
        .build()
//Retrofit实例化
retrofit = Retrofit.Builder()
    .baseUrl(BaseConstant.SERVICE_HOST)
    .addConverterFactory(GsonConverterFactory.create())
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .client(client)
    .build()

 

你可能感兴趣的:(Android)