如何使用Retrofit2 + RxJava添加Authorization标头

Vik*_*kov 4 android retrofit retrofit2

我想使用Retrofit2和RxJava执行请求

public static Observable<Post> getPostsAround(Location location, int offset, int limit) {
    if(api==null) {
        new RestService();  //initialize API in constructor
    }
    return api.getPostsAround(location.getLatitude(),location.getLongitude(),offset,limit)
            .flatMapIterable(posts -> posts);   //transform Observable<List<Post>> to Observable<Post> which emits posts onNext
}
Run Code Online (Sandbox Code Playgroud)

我尝试了@Headers("授权:代码")注释,但我不知道如何在运行时更改"代码".

Vik*_*kov 11

我找到了答案:可以使用@Header注释动态更新请求标头.必须为@Header提供相应的参数.如果该值为null,则将省略标头.否则,将在值上调用toString,并使用结果.

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
Run Code Online (Sandbox Code Playgroud)