【问题标题】:Getting org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type for Spring Rest webservices获取 org.springframework.web.client.HttpClientErrorException: 415 Spring Rest webservices 不支持的媒体类型
【发布时间】:2018-12-15 12:25:38
【问题描述】:

获取 Spring Rest 控制器 Web 服务的以下异常:-

org.springframework.web.client.HttpClientErrorException: 415 不支持的媒体类型 在 org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) 在 org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)

代码:

public class PaymentProcessController {

@RequestMapping(value = "/payment_failure", method = RequestMethod.POST)


    public ModelAndView savePayFailure(HttpServletRequest request, HttpServletResponse response, HttpSession session)
{
        RestTemplate restTemplate = new RestTemplate();
       Invoice invoice = restTemplate.getForObject(
                    "http://localhost:8080/rooftop/invoice/findByProperty/TRANASACTION_NO/" + tx
nid, Invoice.class);


}

REST 客户端在 InvoiceRestController 中编写如下:

InvoiceRestController:

  @RestController @RequestMapping(value = "/invoice/") 

public class
            InvoiceRestController {     @RequestMapping(value =
            "/findByProperty/{property}/{value}", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE, consumes =
            MediaType.APPLICATION_JSON_VALUE)

  public ResponseEntity<Invoice> findByProperty(@PathVariable String property, @PathVariable String value) throws Exception {

        }

【问题讨论】:

  • 请提出解决方案
  • 您使用什么客户端来调用savePayFailure aka payment_failure 映射?
  • payment_failure 是客户端,是 Spring mvc 前端控制器

标签: resttemplate spring-rest


【解决方案1】:

这个问题在您的设置中非常本地化,所以我想无法提供通用答案。只有调试问题的步骤。

1. 首先确保 Http 消息转换器就位,即类路径中包含像 jackson 这样的库,如果包含库,请确保 jar 没有损坏。有时,这就是您遇到错误的原因。

这个库自动包含在 Spring Boot 中。

如果不使用任何框架,您可能需要执行 this 之类的操作

2. 其次,当您从savePayFailure 拨打休息电话时,请确保在RestTemplate 中设置并传递适当的内容协商标头,例如AcceptContent-Type

你的 rest api 很清楚它消耗什么和产生什么,但是在调用 api 时,你没有设置任何这样的期望。由于这是您的自定义客户端,因此您需要设置来转换消息和标头。

How to set an “Accept:” header on Spring RestTemplate request?

HTTP get with headers using RestTemplate

Add my custom http header to Spring RestTemplate request / extend RestTemplate

您按该顺序尝试这两个步骤并使用更新的代码更新问题。

【讨论】:

  • 谢谢,但内容已经根据您提到的要点进行了更新。在这里,我们需要使用 restTemplate 交换值作为 /findByProperty/{property}/{value} 的专业知识
  • 当您调用 /findByProperty/{property}/{value} 时,将向 api 发送一个 http 请求,您需要为该 resttemplate 调用设置这些标头,因为您的 jsp 控制器现在是客户端。每个客户端(swagger,邮递员等等)设置这些标题。
猜你喜欢
  • 1970-01-01
  • 2017-06-30
  • 2017-10-31
  • 1970-01-01
  • 2013-01-13
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多