用Retrofit发送请求中添加身份验证
====================
在安卓应用开发中, retrofit可以极大的方便发送http网络请求,不管是GET, POST, 还是PUT, DELETE, Retrofit使用起来都非常简单。只要稍微看一下文档,就知道怎么用。但文档没有具体说明怎么怎么发送带auth信息的请求。本文分享两个代码片段。
比如要发送这样的请求,在header中添加身份验证信息,用户名和密码:
http -a user1:user1password POST http://127.0.0.1/add/ alphago="win"
首先需要把身份验证信息用Base64转码。
``````java
// 首先要把登录信息用Base64 encode
String credentials = user1 + ":" + user1password;
final String auth_string =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
``````
有两种方法可以实现,方法一是直接添加header信息,方法二是使用拦截器
####方法一
在请求的头中添加的,在api接口定义时添加,使用Header decorator.
''' java
public interface apiInterface{
@POST("add/")
call<User> authUser(@Header("Authorization") String auth);
} apiInterfaceService.addNew(auth_string);
'''
####方法二
通过OkHttpClient.Builder的addIntercepoter添加Interceptor, 在request中添加头文件信息,通过okhttpclient添加到retrofit,
''' java
private static Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()); private static OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", auth_string)
.header("Accept", "application/json")
.method(original.method(), original.body()); Request request = requestBuilder.build();
return chain.proceed(request);
}
});
} OkHttpClient client = httpClientBuilder.build();
retrofitBuilder.client(client).build();
'''