通过@Header 或者@Headers 去添加
区别是 @Header 需要写到参数位置,用于指定可变的头信息
而@Headers 则作用于方法,用于指定固定的头信息
如:
再比如
当然了,如果大家习惯使用通过OkHttpClient设置的话,也是可以的
原文: https://blog.csdn.net/sk719887916/article/details/52189602
添加统一通用header, 不会覆盖前面的header
okHttpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request()
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("header-key", "value1")
.addHeader("header-key", "value2")
Request request = requestBuilder.build()
return chain.proceed(request)
}
})
添加统一通用header, 会覆盖前面的header
okHttpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request()
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("headerkey", "header-value")// <-- this is the important line
Request request = requestBuilder.build()
return chain.proceed(request)
}
})
统一添加参数
OkHttpClient.Builder httpClient =
new OkHttpClient.Builder()
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request()
HttpUrl originalHttpUrl = original.url()
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("apikey", "your-actual-api-key")
.build()
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.url(url)
Request request = requestBuilder.build()
return chain.proceed(request)
}
})
获取方法有两种获取Response Headers的方法
直接在定义接口是让接口返回Retrofit的Response对象,
在Response对象中可以获取到Headers
2. 在构建Retrofit的APIService时,
在OkHttpClient中加入Interceptor,用以拦截请求和响应获取请求头和响应头。
此方法可用于Retrofit2和OKHttp3.
Interceptor必须在OkHttpClient构建时加入,
OKHttpClient的interceptors()方法返回的是一个不可编辑的列表,
如果对其进行修改 *** 作,会产生UnSupportedOperationException。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)