异步任务省略了OnResponse功能

时间:2016-07-26 09:24:14

标签: android

我在android中编写了登录活动。我想这就像这里的异步任务是我的代码

   public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
      boolean succes;
    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {

        Retrofit retrofit = LoginService.buildRetrofit();
        LoginApiInterface apiService = retrofit.create(LoginApiInterface.class);
        Call<LoginPojo> login = apiService.login(mEmail, mPassword);
        login.enqueue(new Callback<LoginPojo>() {
            @Override
            public void onResponse(Call<LoginPojo> call, Response<LoginPojo> response) {
                int c = response.raw().code();
                if (c == 200) {
                    succes = true;
                    token = response.body().getAuthorization();
                } else {
                    succes = false;
                    mPasswordView.setError(getString(R.string.error_incorrect_password));
                }
            }
            @Override
            public void onFailure(Call<LoginPojo> call, Throwable t) {
                succes = false;
                mPasswordView.setError(getString(R.string.error_incorrect_password));
            }
        });


        return succes;
    }

一切看起来都很好,但它只运行代码直到调用然后它总是返回成功变量(我知道它是假的,因为没有授权)

1 个答案:

答案 0 :(得分:0)

如果条件为if(c==200),则不应检查响应代码。响应代码表示网络响应正常。除非网络响应错误/服务器故障,否则它将始终返回200。

如果要检查api返回成功,则必须从服务器返回成功代码

 int c = response.body().getstatus();
                if (c == 1) {
                    succes = true;
                    token = response.body().getAuthorization();
                } else {
                    succes = false;
                        mPasswordView.setError(getString(R.string.error_incorrect_password));
                }