【问题标题】:Spring - RestTemplate throwing InvalidMediaTypeExceptionSpring - RestTemplate 抛出 InvalidMediaTypeException
【发布时间】:2014-04-01 02:23:11
【问题描述】:

我正在开发 Spring RestTemplate,在执行以下代码后我得到了InvalidMediaTypeException。当我在 RestClient 应用程序中执行相同的服务时,我得到了有效的响应。请帮忙。

ResponseEntity<String> response = restTemplate.exchange(restUrl,HttpMethod.valueOf(method), new HttpEntity<byte[]>(headers), String.class);

下面是堆栈跟踪。

org.springframework.http.InvalidMediaTypeException: Invalid media type "multipart/mixed;boundary=simple boundary;charset=UTF-8": Invalid token character ' ' in token "simple boundary"
    at org.springframework.http.MediaType.parseMediaType(MediaType.java:730)
    at org.springframework.http.HttpHeaders.getContentType(HttpHeaders.java:305)
    at org.springframework.web.client.HttpMessageConverterExtractor.getContentType(HttpMessageConverterExtractor.java:113)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:84)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:687)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:673)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:446)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:393)
    at com.restclient.helper.RestHelper.getResponse(RestHelper.java:28)

【问题讨论】:

  • 标题中有什么?
  • content-type:application/x-www-form-urlencoded 是标题。该方法是 GET 并将所有参数作为 URL 的一部分传递。

标签: java spring exception resttemplate media-type


【解决方案1】:

这是因为客户端内容类型和服务器接受的内容类型不匹配。 基本上正常的“GET”方法默认内容类型是“text/plain”,但你的案例服务器需要的东西不是“text/plain”。因此,当您向服务器发送请求时,您应该更改标头的内容类型

【讨论】:

    【解决方案2】:

    Spring 非常严格地解析响应的Content-Type。正如错误消息所暗示的那样,Content-Type 字段中不允许使用空格字符(除非被引用)。您可以在RFC 2616 section 2.2RFC 2045 section 5.1 中了解它。确保您调用的服务器符合这些规则。

    【讨论】:

    • 如果我没记错的话,空格字符是响应内容类型的一部分。我该怎么做才能避免这种情况?
    • @RajaAsthana 谁在运行服务器应用程序?应该纠正的是服务器端;目前它似乎发送语法错误的响应。
    • @RajaAsthana 其他 REST 客户端很可能会进行更“宽松”(不那么严格)的解析。
    【解决方案3】:

    异常和堆栈跟踪说明了一切:

    在客户端你有:

    ResponseEntity<String> response 
        = restTemplate.exchange(
            restUrl,
            HttpMethod.valueOf(method), 
            new HttpEntity<byte[]>(headers), // <-- contains bad "Content-Type" value
            String.class);
    

    headers 映射包含

    "Content-Type" -> "multipart/mixed;boundary=simple boundary;charset=UTF-8"`
    

    当请求到达服务器时,它会尝试使用MediaType#parseMediaType(String) 解析此标头值,但空格字符无效,如异常消息所示:

    Invalid token character ' ' in token "simple boundary"

    下一步是调查headers 的填充方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多