android - Android改造响应体,jwt响应,如何获取?
问题描述
我使用 android 作为我的前端应用程序和 Spring boot 作为服务器部分。我正在使用 android 改造库与服务器连接。当用户登录服务器时,他会得到这样的响应。
那么如何从正文响应中提取“accessToken”和“tokenType”呢?
这是我在android中的登录方法:
private void login(LoginRequest loginRequest) {
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClientBuilder.addInterceptor(logging);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClientBuilder.build());
Retrofit retrofit = builder.build();
RestAPI client = retrofit.create(RestAPI.class);
Call<LoginRequest> call = client.signIn(loginRequest);
call.enqueue(new Callback<LoginRequest>() {
@Override
public void onResponse(Call<LoginRequest> call, Response<LoginRequest> response) {
if (response.code() == 200) {
Toast.makeText(getApplicationContext(), response.body().toString(),
Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, PostsActivity.class);
//response.body should be somewhere here
startActivity(i);
}else{
Toast.makeText(getApplicationContext(), "Uneti podaci nisu dobri",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<LoginRequest> call, Throwable t) {
}
});
}
这是我的 LoginRequest 类
public class LoginRequest {
private String username;
private String password;
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
}
}
解决方案
为响应创建模型类,如下所示
public class Token {
@SerializedName("tokenType")
private String tokenType;
@SerializedName("accessToken")
private String accessToken;
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
然后将 Api 返回类型更改为Call<Token>
因此,您还需要修改调用
call.enqueue(new Callback<Token>() {
@Override
public void onResponse(Call<Token> call, Response<Token> response) {
if(response.isSuccessful()) {
Token token = response.body();
}
}
@Override
public void onFailure(Call<Token> call, Throwable t) {
}
});
推荐阅读
- nextflow - Nextflow 具有不同文件数量的多个输入
- java - 多个线程可以执行单个任务,以便快速完成任务吗?在爪哇
- typescript - 键入在构造函数中传递的任意属性
- python-3.x - 如何从不同文件导入函数并在 discord.py 中使用
- python - 删除列的特定行中的值而不删除熊猫数据框中的整行
- javascript - 有没有办法打开网站链接,并使用控制台,使用 JS 在打开的网站上运行自定义代码?
- python - 无法在“文档”上执行“elementsFromPoint”:提供的双精度值是非有限的
- c++ - 使用一个 .so 文件链接但在 LD_LIBRARY_PATH 中设置另一个具有相同 API 的库是否安全?
- c++ - 为什么 const 函数可以使用静态成员对象的非常量函数?
- c# - Gembox 文档删除目录