发送POST请求时发生java-org.springframework.http.converter.HttpMessageNotReadableException

前端之家收集整理的这篇文章主要介绍了发送POST请求时发生java-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,但是我找不到出现这种错误的原因.我将不胜感激任何帮助.提前致谢

最佳答案
您的代码中存在两个问题:

>您尝试将JSON转换为控制器内的对象.
这已经由Spring完成了.它接收请求的主体并尝试将其转换为控制器方法中相应参数的Java类.
>您的控制器方法需要一个字符串:
@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
原文链接:https://www.f2er.com/spring/431584.html

猜你在找的Spring相关文章