【问题标题】:Spring Boot: How to resolve Content-Type when incorrectly received from serverSpring Boot:从服务器错误接收时如何解析 Content-Type
【发布时间】:2019-07-28 08:05:24
【问题描述】:

我在 Java 中有以下课程。我希望它向 url 发出 GET 请求,取回 JSON 有效负载,并将该有效负载转换为 List<LocationData>

package ...
import ...

@Repository
public class ProxiedLocationRepo {

    public List<LocationData> findAll() throws Exception {
        RestTemplate restTemplate = new RestTemplate();

        String url = UriComponentsBuilder
                .fromUriString("https://my-host/path")
                .queryParams("some", "queryParams")
                .toUriString();

        ResponseEntity<List<LocationData>> res = restTemplate.exchange(
                                                     url,
                                                     HttpMethod.GET,
                                                     null,
                                                     new ParameterizedTypeReference<List<LocationData>>(){});

        if (res.getStatusCode() == HttpStatus.ACCEPTED) {
            return res.getBody();
        } else {
            throw new ResponseStatusException(res.getStatusCode(), "Did not receive a 200 response from Server.");
        }
    }
}

但是,我得到了这个错误:

org.springframework.http.InvalidMediaTypeException: Invalid mime type "charset=UTF-8": does not contain '/'

这是意料之中的,因为如果我从 curl 发出相同的请求,并检查我得到的标题(注意 Content-Type 行):

$ curl -sfi 'https://my-host/path?some=queryParams'
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 06 Mar 2019 13:58:58 GMT
Content-Type: charset=UTF-8
Content-Length: 1821
Connection: keep-alive
Vary: Accept-Encoding
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Frame-Options: SAMEORIGIN

... # perfectly formatted JSON payload here

我知道从该服务器返回的 Content-Type 将是 application/json,但它没有提供给我。

是否有通知RestTemplate#exchange 响应的 Content-Type 是什么?如果没有,除了让服务器的所有者正确设置 Content-Type 之外,我还可以使用其他方法来解决此问题吗?

编辑: 我也尝试添加“接受”标题,但得到了相同的结果:

$ curl -sfi 'https://my-host/path?some=queryParams' \
    -H 'Accept: application/json'

【问题讨论】:

  • 您是否尝试在 curl 中设置正确的Content-Type request header?请参阅 -H 参数的用法。
  • 感谢您的提示!我试过了,如果我将内容类型设置为-H 'Content-Type: application/json',请求实际上会失败
  • 我也试过-H 'Accept: application/json'。该请求为此工作,但返回的 Content-Type 仍然只是“charset=UTF-8”
  • 修复服务器?
  • " 除了让服务器的所有者正确设置 Content-Type 之外,我还可以使用其他方法来解决此问题吗?"

标签: java spring-boot http networking mime-types


【解决方案1】:

不幸的是,我认为在利用 Spring 框架时没有任何方法可以解决此问题。即使您要创建一个接受 MIME 类型 ANY 的自定义 JsonbHttpMessageConverter,Spring 仍然无法解析从请求中收到的不正确的 Content-Type(因为它在 Content-Type 字符串中找不到 "/" )。

所以这里的解决方案是使用java.net.HttpURLConnection 来代替网络,然后使用com.fasterxml.jackson.databind.ObjectMapper 从 JSON 映射到 POJO。

它可以工作,但代价是不再能够利用 Spring 的任何 HTTP 处理,这可能比我单独实现的任何东西都要强大得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多