繁体   English   中英

如果状态代码为400,且在Android中进行了改装,则在响应错误正文上接收NULL

[英]Receiving NULL on response error body if the status code is 400 with retrofit in android

我在进行某些登录过程时陷入困境。 问题是当我输入错误的密码时,它总是抛出NullPointerException,因为我的getMessage从后端收到了空响应。 之后,我所做的就是将节点中的状态代码从400更改为200(我正在使用200表示成功状态),然后尝试相同的过程。这次输入了错误的密码后,它给了我来自节点的响应。

这意味着我的改装没有收到状态码400的响应,而将其更改为200时,效果很好,这确实很奇怪。

如果您希望我能发布我的登录名或节点代码,那么谁都知道为什么会这样。

谢谢 !

编辑

这是我在登录活动中的onResponse方法。

 public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

            if (resp.getmessage().equals(Constants.SUCCESS))
            {
                Toast.makeText(Login.this, resp.getmessage(), Toast.LENGTH_SHORT).show();
                goToProfile();

        }
        else {
                Toast.makeText(Login.this, resp.getmessage(), Toast.LENGTH_SHORT).show();
            }

        }

这是我的节点代码,当前所有状态代码都是200,但是当我使用400输入错误的密码并且用户未找到密码时,它将返回null。

const User= require("../model/user.model.js");
const { initSession} = require('../utils/utils');

const logins =  (req,res,next)=> {  
console.log("login user::"+JSON.stringify(req.body));
console.log("password:::"+req.body.user.password);  
 User.findOne({ username : req.body.user.username }, function(err, user) {
    if (!user) {           
          return res.status(200).send({
              message : "User not found."
          });
      }    
      else {    

        if (user.validPassword(req.body.user.password)) {   
            console.log("login successfully!!!");            
            return res.status(200).send({
                message : "success"
            });

        }        
    else if(!(user.validPassword(req.body.user.password))) {
        console.log("wrong password");
        return res.status(200).send({
            message : "Wrong Password"
        });
    }
}
  })
  }

module.exports = { logins };

当您收到错误改进时,不会解析它,而是将其作为errorBody传递。

因此,您需要将此json: response.errorBody().string()解析为ServerResponse对象,然后才能访问message属性。

编辑:

您的响应功能:

public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
    if(response.isSuccessful()) {
        ServerResponse serverResponse = response.body()
        if(serverResponse.getMessage().equals(Constants.SUCCESS)) {
            Toast.makeText(Login.this, response.body().getMessage()).show();
            goToProfile();
        } else {
            Toast.makeText(Login.this, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
        }
    } else {
        Gson gson = new Gson();
        ServerResponse errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
        Toast.makeText(Login.this, errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

暂无
暂无

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

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