Java 如何在 Retrofit 2.0 中使用拦截器添加标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32963394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use interceptor to add Headers in Retrofit 2.0?
提问by hackjutsu
Our team decide to adopt Retrofit 2.0and I'm doing some initial research on it. I'm a newbie to this library.
我们的团队决定采用Retrofit 2.0,我正在对它进行一些初步研究。我是这个图书馆的新手。
I'm wondering how to use interceptor
to add customized headers via Retrofits 2.0in our Android app. There are many tutorialsabout using interceptor
to add headers in Retrofit 1.X, but since the APIs have changed a lot in the latest version, I'm not sure how to adapt those methods in the new version. Also, Retrofit hasn't update its new documentation yet.
我想知道如何在我们的 Android 应用程序中interceptor
通过Retrofits 2.0添加自定义标题。有很多关于在 Retrofit 1.X 中使用添加标头的教程interceptor
,但由于最新版本的 API 发生了很大变化,我不确定如何在新版本中调整这些方法。此外,Retrofit 尚未更新其新文档。
For example, in the following codes, how should I implement the Interceptor
class to add extra headers? Besides, what exactly is the undocumented Chain
object? When will the intercept()
be called?
例如,在下面的代码中,我应该如何实现Interceptor
该类以添加额外的标头?此外,无证Chain
对象究竟是什么?什么时候会intercept()
叫?
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// How to add extra headers?
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
采纳答案by EpicPandaForce
Check this out.
看一下这个。
public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("appid", "hello")
.addHeader("deviceplatform", "android")
.removeHeader("User-Agent")
.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
.build();
Response response = chain.proceed(request);
return response;
}
}
Kotlin
科特林
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain.run {
proceed(
request()
.newBuilder()
.addHeader("appid", "hello")
.addHeader("deviceplatform", "android")
.removeHeader("User-Agent")
.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
.build()
)
}
}
回答by VenomVendor
Another alternative from the accepted answer
已接受答案的另一种选择
public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.addHeader("headerKey0", "HeaderVal0")
.addHeader("headerKey0", "HeaderVal0--NotReplaced/NorUpdated") //new header added
.build();
//alternative
Headers moreHeaders = request.headers().newBuilder()
.add("headerKey1", "HeaderVal1")
.add("headerKey2", "HeaderVal2")
.set("headerKey2", "HeaderVal2--UpdatedHere") // existing header UPDATED if available, else added.
.add("headerKey3", "HeaderKey3")
.add("headerLine4 : headerLine4Val") //line with `:`, spaces doesn't matter.
.removeAll("headerKey3") //Oops, remove this.
.build();
request = request.newBuilder().headers(moreHeaders).build();
/* ##### List of headers ##### */
// headerKey0: HeaderVal0
// headerKey0: HeaderVal0--NotReplaced/NorUpdated
// headerKey1: HeaderVal1
// headerKey2: HeaderVal2--UpdatedHere
// headerLine4: headerLine4Val
Response response = chain.proceed(request);
return response;
}
}
回答by Fawad Badar
public class ServiceFactory {
public static ApiClient createService(String authToken, String userName, String password) {
OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
.addInterceptor(
chain -> {
Request request = chain.request().newBuilder()
.headers(getJsonHeader(authToken))
.build();
return chain.proceed(request);
})
.authenticator(getBasicAuthenticator(userName, password))
.build();
return getService(defaultHttpClient);
}
private static Headers getJsonHeader(String authToken) {
Headers.Builder builder = new Headers.Builder();
builder.add("Content-Type", "application/json");
builder.add("Accept", "application/json");
if (authToken != null && !authToken.isEmpty()) {
builder.add("X-MY-Auth", authToken);
}
return builder.build();
}
private static Authenticator getBasicAuthenticator(final String userName, final String password) {
return (route, response) -> {
String credential = Credentials.basic(userName, password);
return response.request().newBuilder().header("Authorization", credential).build();
};
}
private static ApiClient getService(OkHttpClient defaultHttpClient) {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(defaultHttpClient)
.build()
.create(ApiClient.class);
}
}
回答by Fawad Badar
You can headers using Interceptors with its built-in methods like this
您可以使用 Interceptors 及其内置方法来标头,如下所示
interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder();
builder.header("Authorization","Bearer "+ LeafPreference.getInstance(context).getString(LeafPreference.TOKEN));
Request request = builder.method(original.method(), original.body())
.build();
Log.e("request",request.urlString());
Log.e("header",request.header("Authorization"));
return chain.proceed(request);
}
});
}