英文:
Trying to get to api
问题
public List<FootballDto> getFootballs() {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Auth-Token", "YOUR_TOKEN_HERE"); // Replace YOUR_TOKEN_HERE with your actual token
FootballDto[] footballResponse = restTemplate.exchange(
"https://api.football-data.org/v2/competitions/SA/scorers",
HttpMethod.GET,
new HttpEntity<>(headers),
FootballDto[].class
).getBody();
}
英文:
I try to get to this api : https://www.football-data.org/. I have key and token name. From Postman I can get to this api by "Api Key" autorization with name : X-Auth-Token and token XXXX. But how can I do this from java with rest template ? How should i put my headers to this url:
public List<FootballDto> getFootballs() {
HttpHeaders headers = new HttpHeaders();
headers.add(tokenName,token);
FootballDto[] footballResponse = restTemplate.getForObject(
"https://api.football-data.org/v2/competitions/SA/scorers", FootballDto[].class
);
}
Thanks a lot
答案1
得分: 1
The RestTemplate getForObject()
method doesn't support setting headers. The solution is to use the exchange()
method. So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use:
HttpHeaders headers = new HttpHeaders();
headers.set("Header-1", "value-1");
headers.set("Header-2", "value-2");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
英文:
The RestTemplate getForObject()
method doesn't support setting headers. The solution is to use the exchange()
method. So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use:
HttpHeaders headers = new HttpHeaders();
headers.set("Header-1", "value-1");
headers.set("Header-2", "value-2");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论