【问题标题】:Spring Boot HttpMediaTypeNotSupportedExceptionSpring Boot HttpMediaTypeNotSupportedException
【发布时间】:2023-03-12 14:41:01
【问题描述】:

我目前正在思考为什么包含参数@RequestBody Car car 会破坏我的终点。

我对 Spring boot 非常陌生,并试图将 json 字符串发布到我的休息控制器。

这是我的控制器:

@RestController
@RequestMapping("/v1/car")
@EnableWebMvc
public class CarController  {

private static final Log LOGGER = LogFactory.getLog(CarController.class);

@Autowired
private CarService carService;


@RequestMapping(value="/{accountId}", method = RequestMethod.POST, consumes={"text/plain", "application/*"})
ResponseEntity<?> start(@PathVariable final Integer accountId, @RequestBody Car car) {
    System.out.println("E: "+accountId);
    final long tid = Thread.currentThread().getId();
    final Boolean status = this.smarterWorkFlowService.startWorkFlow(accountId, car);
    return new ResponseEntity<Car>(new Car(), HttpStatus.ACCEPTED); 
}
}

我也使用 jackson 作为我的 json 解析器。我找了好几个小时,但没有发现任何东西可以帮助我解释为什么我收到了 415 回复。

{ "timestamp": 1425341476013, "status": 415, "error": "Unsupported Media Type", "exception": "org.springframework.web.HttpMediaTypeNotSupportedException", "message": "Unsupported Media Type", "path": "/v1/experiences/12" }

感谢您的帮助!!

【问题讨论】:

    标签: json spring spring-mvc jackson spring-boot


    【解决方案1】:

    首先,在 spring boot 中 @EnableWebMvc 是不需要的。然后,如果您的 REST 服务需要生成 json 或 xml,请使用

    @RequestMapping(value = "properties", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.POST)
    

    测试你的服务

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-type", header);
    headers.add("Accept", header);
    
    UIProperty uiProperty = new UIProperty();
    uiProperty.setPassword("emelendez");
    uiProperty.setUser("emelendez");
    
    HttpEntity entity = new HttpEntity(uiProperty, headers);
    
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties/1", HttpMethod.POST, entity,String.class);
    return response.getBody();
    

    将标题替换为application/jsonapplication/xml。如果你使用的是xml,添加这个依赖

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
    

    【讨论】:

    • 感谢您的回复!该服务只需要生成 JSON。我确实添加了produces参数,但在测试POSTMan chrome应用程序时仍然出现415错误。我的休息服务需要接受 POST 方法。我已验证我发送的内容类型正确。
    • 抱歉,我忘记更新我的问题了,现在你可以尝试一些更改。
    【解决方案2】:

    如果您使用的是 JSON,请删除 @RequestMappingconsumes={...} 部分,确保您实际上是在发布 JSON 并将 Content-type 设置为 application/json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2021-06-11
      • 2021-04-02
      • 1970-01-01
      • 2014-04-07
      • 2014-04-07
      • 2016-01-29
      相关资源
      最近更新 更多