Android Retrofit Call pass response.body() 作为参数进行处理

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

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

我的 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;
    }
}

我调用的函数(点击登录按钮后调用):

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(); 来保存更改。