首页 > 解决方案 > 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;
}

}  

标签: androidspringloginretrofit2

解决方案


为响应创建模型类,如下所示

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) {
    }
});

推荐阅读