无法读取HTTP消息:org.springframework.http.converter.HttpMessageNotReadableException

时间:2018-09-28 07:56:07

标签: java spring spring-mvc spring-boot

我遇到URL时遇到问题

我的控制器

  
    

请帮助我从标题中查找错误

  
  @RestController
    @RequestMapping("/client")
    public class TestController {

        @PostMapping(produces = { "application/json", "application/xml" })

    public ResponseEntity<Client> createCustomer(@RequestBody Client customer) {

            System.out.println("Creat Customer: " + customer);

            return ResponseEntity.ok(customer);
        }

    }

1 个答案:

答案 0 :(得分:0)

如果您的Spring Web MVC正常,请尝试使用此方法。

@RequestMapping(value="client", produces = { "application/json", "application/xml" })
public @ResponseBody Customer createCustomer(
    @RequestParam Customer customer) {

        ...do some work like customerDao.create(customer);

        System.out.println("Create Customer: " + customer);

        return customer;
}

如果这是REST接口,则需要首先反序列化传入的数据。如果您的数据是xml,则可以执行例如使用JAXB2-Marshaller。如果您具有JSON数据,则可以以相同方式使用FasterXML(Jackson)。您的代码可能看起来像

@RequestMapping(value="client", produces = { "application/json", "application/xml" })
public @ResponseBody Customer createCustomer(
    @RequestBody String body) {

        Source source = new StreamSource(new StringReader(body));
        RestRequest restRequest = (RestRequest)jaxb2Marshaller.unmarshal(source);

        Customer customer = (Customer) restRequest.getRequestData();

        ...do some work like customerDao.create(customer);

        System.out.println("Create Customer: " + customer);

        return customer;
}