【发布时间】: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