繁体   English   中英

Android Retrofit 调用传递response.body()作为参数进行处理

[英]Android Retrofit Call pass response.body() as paramater for processing

我想知道如何将 response.body() 作为参数传递以进一步处理它。 因为现在我只能将它传递给 Toast 或 textView 的 setText,它工作得很好。 但是,如果我尝试将它传递给 function 将其保存到 SharedPrefs 或类似的东西,它只会传递 null object。 我不明白为什么第一个有效,但第二个无效,区别在哪里?

我的 JSon 响应体如下所示:

{
    "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBhZG1vbi5jb20iLCJleHAiOjE1OTQ2NTQ0NjF9.4meOycRP4wbx6hVCJntxH71E03jMYJhg484zCGInUDh6EKPPVDlOhEkCC3X2mjPaCHVfT0qhiulBnC39uh4WEQ"
}

我的 Pojo 是这样的:

public class LoginResponse {

    @Expose
    @SerializedName("Authorization")
    private String authToken;

    public LoginResponse(String authToken) {
        this.authToken = authToken;
    }


    public void setAuthToken(String authToken) {
        this.authToken = authToken;
    }

    public String getAuthToken() {
        return authToken;
    }
}

我进行呼叫的 function (在点击登录按钮后调用):

private void loginCustomer() {
        LoginRequest loginRequest = new LoginRequest(editTextUsername.getText().toString(), editTextPassword.getText().toString());

        Call<LoginResponse> loginCall = ApiUtils.getApi().login(loginRequest);
        loginCall.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(@NotNull Call<LoginResponse> call, @NotNull Response<LoginResponse> response) {
                if (!response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "User Credentials Wrong", Toast.LENGTH_SHORT).show();
                } else {
                    if (response.body() != null) {

// this does not work
                        authToken = response.body().getAuthToken();
                        saveToken(authToken);

 //this does not work either                       SharedPreferences.Editor editor = sp.edit();
                        editor.putString("authToken", response.body().getAuthToken());

//                        openUserMainActivity();
// this works                        Toast.makeText(LoginActivity.this, response.code() + " " + response.body().getAuthToken(), Toast.LENGTH_SHORT).show();
// this does not work                        Toast.makeText(LoginActivity.this, sp.getString("authToken", "no token"), Toast.LENGTH_SHORT).show();

                    }


                }
            }

任何帮助将不胜感激。 提前致谢!

你忘了打电话editor.apply(); editor.commit(); 为了保存更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM