尝试访问 API

huangapple go评论76阅读模式
英文:

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&lt;FootballDto&gt; getFootballs() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(tokenName,token);
        FootballDto[] footballResponse = restTemplate.getForObject(
                &quot;https://api.football-data.org/v2/competitions/SA/scorers&quot;, FootballDto[].class
        );
    }

Thanks a lot 尝试访问 API

答案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(&quot;Header-1&quot;, &quot;value-1&quot;);
 headers.set(&quot;Header-2&quot;, &quot;value-2&quot;);
 ...

 HttpEntity entity = new HttpEntity(headers);

 ResponseEntity&lt;String&gt; response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

huangapple
  • 本文由 发表于 2020年5月29日 20:12:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/62085687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定