Android改装响应主体,jwt作为响应,如何获取呢?

时间:2018-09-09 15:51:21

标签: android spring login retrofit2

我正在使用android作为我的前端应用程序,并使用Spring boot作为服务器部分。我正在使用android改造库与服务器连接。 当用户登录服务器时,他会收到这样的响应。

response from server after successful sign in

那么我该如何从正文响应中提取“ 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;
}

}  

1 个答案:

答案 0 :(得分:0)

创建模型类以进行如下响应

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