【问题标题】:Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException无法读取 HTTP 消息:org.springframework.http.converter.HttpMessageNotReadableException
【发布时间】:2018-09-28 07:56:07
【问题描述】:

我在点击 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);
        }
    
    }

【问题讨论】:

  • ok - 使用给定正文和状态设置为 OK 创建 ResponseEntity 的快捷方式。 - 你为什么认为 customer 对象会是一个身体好吗?
  • 确保您能够序列化和反序列化 Client 类型的对象(即正确配置了 jackson)。

标签: java spring spring-mvc spring-boot


【解决方案1】:

如果你有一个“普通的”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;
}

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 2011-01-12
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2020-11-16
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多