Retrofit-Android上的token验证

75 篇文章 0 订阅
65 篇文章 0 订阅

这篇文章是一个除了前面的帖子使用retrofit进行基本的身份验证和使用基于OAuth的基本APIS。我们将讨论的话题token认证从一个Android应用到任何网络服务或API支持这种认证。

Integrate Token Authentication

如果你读前面的帖子关于使用retrofit的身份验证,你会猜到我们要怎么做:扩展ServiceGenerator类和集成方法处理token认证。让我们直接与第二个扩展ServiceGenerator createService方法:

Retrofit 1.9
public class ServiceGenerator {

   
public static final String API_BASE_URL = "https://your.api-base.url";

   
private static RestAdapter.Builder builder = new RestAdapter.Builder()
               
.setEndpoint(API_BASE_URL)
               
.setClient(new OkClient(new OkHttpClient()));

   
public static <S> S createService(Class<S> serviceClass) {
       
return createService(serviceClass, null);
   
}

   
public static <S> S createService(Class<S> serviceClass, final String authToken) {  
     
if (authToken != null) {
          builder
.setRequestInterceptor(new RequestInterceptor() {
             
@Override
             
public void intercept(RequestFacade request) {
                  request
.addHeader("Authorization", authToken);
             
}
         
});
     
}

     
RestAdapter adapter = builder.build();
     
return adapter.create(serviceClass);
   
}
}
Retrofit 2
public class ServiceGenerator {

   
public static final String API_BASE_URL = "https://your.api-base.url";

   
private static OkHttpClient httpClient = new OkHttpClient();
   
private static Retrofit.Builder builder =
           
new Retrofit.Builder()
                   
.baseUrl(API_BASE_URL)
                   
.addConverterFactory(GsonConverterFactory.create());

   
public static <S> S createService(Class<S> serviceClass) {
       
return createService(serviceClass, null);
   
}

   
public static <S> S createService(Class<S> serviceClass, final String authToken) {
       
if (authToken != null) {
            httpClient
.interceptors().clear();
            httpClient
.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("Authorization", authToken)
                           
.method(original.method(), original.body());

                   
Request request = requestBuilder.build();
                   
return chain.proceed(request);
               
}
           
});
       
}

       
Retrofit retrofit = builder.client(httpClient).build();
       
return retrofit.create(serviceClass);
   
}
}

正如你所看到的,我们通过身份验证标记作为一个字符串变量方法,使用RequestInterceptor(Interceptor in Retrofit 2)设置HTTP标头字段进行授权。如果你使用另一个HTTP报头字段为您的身份验证token,上面的代码调整或创建一个新的方法处理所需的功能。

从现在开始,每一个HTTP客户端创建该方法集成了令牌授权头字段的值,并自动传递token值与任何请求API端点。

Example Usage

让我们创建一个例子,看看一些代码。下面的UserService接口声明一个方法叫me()。这个示例方法返回一个用户对象从API创建响应。

Retrofit 1.9
public interface UserService {  
    @POST
("/me")
   
User me();
}
Retrofit 2
public interface UserService {  
    @POST
("/me")
   
Call<User> me();
}

要特殊照顾调用API等待在终点HTTP任何要求://your.api-base.url/me并要求身份验证以获取用户数据的响应。现在,让我们创建一个用户服务对象,做实际的请求 .

Retrofit 1.9
UserService userService =  
   
ServiceGenerator.create(UserService.class, "auth-token");
User user = userService.me();
Retrofit 2
UserService userService =  
   
ServiceGenerator.create(UserService.class, "auth-token");
Call<User> call = userService.me();  
User user = call.execute().body();

这段代码演示了如何使用了类。当然,你必须要经过实际验证token值ServiceGenerator方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
retrofit-spring-boot-starter是一个用于整合Retrofit库和Spring Boot的starter项目,它可以简化在Spring Boot中使用Retrofit的配置和使用。 以下是retrofit-spring-boot-starter的使用方法: 1. 在你的Spring Boot项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.github.lianjiatech</groupId> <artifactId>retrofit-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> ``` 2. 创建一个接口,用于定义Retrofit的API接口。例如: ```java import retrofit2.http.GET; import retrofit2.http.Path; public interface MyApi { @GET("/users/{username}") User getUser(@Path("username") String username); } ``` 3. 在你的Spring Boot应用程序中,使用`@Autowired`注解将Retrofit的API接口注入到你的代码中。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import retrofit2.Retrofit; @Service public class MyService { private final MyApi myApi; @Autowired public MyService(Retrofit retrofit) { this.myApi = retrofit.create(MyApi.class); } public User getUser(String username) { return myApi.getUser(username); } } ``` 4. 现在你可以在你的代码中使用`MyService`来调用Retrofit的API接口了。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { private final MyService myService; @Autowired public MyController(MyService myService) { this.myService = myService; } @GetMapping("/users/{username}") public User getUser(@PathVariable String username) { return myService.getUser(username); } } ``` 以上是retrofit-spring-boot-starter的基本用法。你可以根据自己的需求进行配置和使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百世修行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值