簡體   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