改造:2.0.0-beta2 http呼叫和响应处理

时间:2015-11-30 23:03:00

标签: retrofit

我的后端返回此json对象以表示成功的新用户注册 {   “错误”:错误,   “消息”:“您已成功注册” }

这表示帐户已经存在 {   “错误”:是的,   “message”:“抱歉,此电子邮件已存在” }

这和其他注册失败有关 {   “错误”:是的,   “消息”:“发生错误!!请再试一次” }

我想使用改造:2.0.0-beta2进行异步http调用并处理响应以将其用于主页或相应地重定向到登录页面。

这是我的POJO: 公共类用户{

public final String email, firstname, lastname, city, birthday, gender, password;

public User(final String email, final String firstname, final String lastname,
            final String city, final String birthday, final String gender, final String password) {
    this.email = email;
    this.firstname = firstname;
    this.lastname = lastname;
    this.city = city;
    this.birthday = birthday;
    this.gender = gender;
    this.password = password;
}

} 这是我的服务: 公共接口APIService {

@POST("/api/user")
Call<User> createUser(@Body User user);

}

2 个答案:

答案 0 :(得分:0)

您需要创建一个额外的类来处理响应。

public class ResponseApi{
    public String error;
    public String message;
}

你是个地方

@POST("/api/user")
Call<ResponseApi> createUser(@Body User user);

答案 1 :(得分:0)

您需要实现onResponse侦听器并处理重定向或其中的任何其他操作。

例如:

  protected void loginAttempt(final View v) {
    authUser = new HashMap<>();
    authUser.put("email", email.getText().toString());
    authUser.put("password", password.getText().toString());

    Call call = SubApplication.api.authUser(authUser);
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            try {
                JSONObject responseObject = new JSONObject(new Gson().toJson(response.body()));
                Log.d("LoginActivity", "onResponse: " + responseObject.toString());

                if (responseObject.getBoolean("success") == true) {
                    Toast.makeText(v.getContext(), getString(R.string.error_login_success), Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(v.getContext(), DashboardActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(v.getContext(), getString(R.string.error_login_failed), Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Log.e("LoginActivity", "Exception: " + e);
                Toast.makeText(v.getContext(), getString(R.string.error_login_failed), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.e("LoginActivity", "onFailure: " + t);
        }
    });