发送 POST 请求时出现 org.springframework.http.converter.HttpMessageNotReadableException

新手上路,请多包涵

我有一个带有以下控制器的 Spring 应用程序:

    @RestController
   @RequestMapping("/app")
   public class RegisterRestController {
   @Autowired
    UserRepository userRepository;

   @Autowired
   PasswordEncoder passwordEncoder;

   @Autowired
   UserService userService;

   @RequestMapping( value="/loginuser", method =RequestMethod.POST,produces="application/json")
    public String loginUser(@RequestBody String requestBody) {
    System.out.println("inside");
    JSONObject responseJsonObject = new JSONObject();
    String phonenumber;
    String password;
    try{
        JSONObject object = new JSONObject(requestBody);
        phonenumber = object.getString("phonenumber");
        password = object.getString("password");
        User user = userService.findByNumber(phonenumber);
        String sha256Password = passwordEncoder.encode(password);
        if(sha256Password.equals(user.getPassword())){
            responseJsonObject.put("response", "Login Successful");
        }
        else {
            responseJsonObject.put("repsonse", "Login failed");
        }
    }
    catch (Exception e){
        e.printStackTrace();
        try {
            responseJsonObject.put("response", "Invalid Credentials");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

    }
    return responseJsonObject.toString();
}

但是,当我从 Postman 发送包含以下内容的 POST 请求时:

     {
      "phonenumber":"9123456789",
      "password":"password"
  }

我收到以下回复:

     {
   "timestamp": 1456043810789,
   "status": 400,
    "error": "Bad Request",
    "exception":      "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "Could not read JSON: Can not deserialize instance of   java.lang.String out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@eaa3acb; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@eaa3acb; line: 1, column: 1]",
    "path": "/app/loginuser"
}

另外,我也在试验 Spring Security。服务器没有显示任何错误,控制器似乎没有收到请求,因为没有打印“内部”。我正在尝试熟悉 Spring,但是我找不到出现这种错误的原因。如果有任何帮助,我将不胜感激。提前致谢

原文由 raptor123 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

您的代码中有两个问题:

  1. 您尝试将 JSON 转换为控制器内的对象。 Spring 已经做到了这一点。它接收请求的主体,并尝试将其转换为控制器方法中相应参数的 Java 类。
  2. 您的控制器方法需要一个字符串: @RequestBody String requestBody

您正在发送一个具有两个属性的对象:

 {
    "phonenumber": "9123456789",
    "password": "password"
}

解决方案:

为您需要登录的值创建一个类:

 public class Login {
    public String phonenumber;
    public String password;
    // you need a zero argument constructor
    // maybe you have to add getter and setters
}

更改您的控制器方法,使其需要这种类型的对象

@RequestBody Login requestBody

原文由 Stefan Isele - prefabware.com 发布,翻译遵循 CC BY-SA 3.0 许可协议

Jackson 库将使用您在登录用户方法中定义的构造函数自动转换为 JSON。所以你不需要转换为json。所以这意味着

{
    "phonenumber": "9123456789",
    "password": "password"
}

应该在你的构造函数中定义。您应该已经定义了一个定义 loginUser 的实体类。

   public class LoginUser{
    String phonenumber;
    String password;

    // define all other variables needed.

    public LoginUser(String phonenumber, String password){
        this.phonenumber = phonenumber ;
        this.password = password;
    }

    public LoginUser() {
        //you need a default contructor. As srequired by spring
    }

    //Define the gettters and settters

}

然后

 @RequestMapping( value="/loginuser", method = RequestMethod.POST,produces="application/json")
    public String loginUser(@RequestBody LoginUser requestBody) {
        System.out.println("inside");
        try{

        phonenumber = requestBody.getPhonenumber; // please define your getters and setters in the login class
        password = requestBody.getpassword;
        User user = userService.findByNumber(phonenumber);
        String sha256Password = passwordEncoder.encode(password);
        if(sha256Password.equals(user.getPassword())){
        responseJsonObject.put("response", "Login Successful");
        }
        else {
        responseJsonObject.put("repsonse", "Login failed");
        }
        }
        catch (Exception e){
        e.printStackTrace();
        try {
        responseJsonObject.put("response", "Invalid Credentials");
        } catch (JSONException e1) {
        e1.printStackTrace();
        }

        }
        return responseJsonObject.toString();
}

你现在可以使用 postman 试试。祝你好运

原文由 uncle-tee 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题