在我的应用程序中,我连接到服务器,必须对我的进一步工作获得成功的响应,在进行此类响应之后,通常,我会得到两个令牌(access + refresh)。对于我的进一步操作,我必须使用访问令牌,因为我将无法获取数据。通常,此令牌会在30分钟后过期。我不明白如何在不失败应用程序的情况下从服务器获取新令牌。我看到了一些问题,这个Refreshing OAuth token using Retrofit without modifying all calls问题是我认为最好的问题。但是我无法理解为我使用它的方式。 现在我正在使用这样的界面:
public interface APIService {
@Headers("Content-type: application/json")
@POST("/v1/login")
Call<Post> auth(@Body Post body);
@Headers({"Content-type: application/json",
"Authorization: Bearer access_token"})
@GET("/v1/message/list")
Call<Message> getInMess(@Query("type") int type, @Query("offset") int offset);
}
然后在我的MainActivity类中初始化我的界面:
public void sendPost()
{
final EditText titleEt = findViewById(R.id.login);
final EditText bodyEt = findViewById(R.id.password);
final String a = titleEt.getText().toString().trim();
final String b = bodyEt.getText().toString().trim();
saveData();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://server/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService mAPIService = retrofit.create(APIService.class);
//retrofit.create(APIService.class);
mAPIService.auth(new Post(a, b)).enqueue(new Callback<Post>() {
@Override
public void onResponse(@NonNull Call<Post> call, @NonNull Response<Post> response) {
if (response.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Post submitted to API.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, SecondScreen.class);
findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#1cd000"), PorterDuff.Mode.MULTIPLY);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Unable to submit post to API.Error!!!", Toast.LENGTH_LONG).show();
findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.MULTIPLY);
}
}
@Override
public void onFailure(@NonNull Call<Post> call, @NonNull Throwable t) {
Toast.makeText(LoginActivity.this, "Unable to submit post to API.", Toast.LENGTH_LONG).show();
}
});
}
请帮助我了解我的进一步发展策略,因为我无法解决自己的问题。
P.S。对不起,我的英语不好))
答案 0 :(得分:0)
您需要拦截请求并将标头添加到拦截器中。我在我的应用程序中使用它:
public class AuthenticationInterceptor implements Interceptor {
public AuthenticationInterceptor(Context context) {
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if(!YOUR_TOKEN.isEmpty()) {
Request authenticatedRequest = request.newBuilder().header("Authorization", "Bearer:" + YOUR_TOKEN).build();
return chain.proceed(authenticatedRequest);
}
return chain.proceed(request);
}
}