我是 API 设计的新手,我正在做一个项目,我需要从波兰国家银行调用货币兑换 API,http://api.nbp.pl 但我没有看到任何迹象表明我在哪里可以找到 API ID。如果我尝试在没有 API ID 的情况下运行应用程序,则此开发是在 Spring 启动上,它会抛出 404 错误。
这是我编写的代码段。
@RequestMapping(method = RequestMethod.GET, value = "/exchangerates/rates/{table}/{code}")
public @ResponseBody Object getAllCurriencyExchangeRates(@PathVariable String table, @PathVariable String code) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
ResponseEntity<Object> response =
restTemplate.getForEntity("http://api.nbp.pl/api/" +table+ "," +code+ Object.class, null, headers);
return response;
}
实际查询 http://api.nbp.pl/api/exchangerates/rates/a/chf/
所以,我的问题是我们可以在没有 API ID 的情况下调用外部 API 吗?
首先,您正在尝试访问错误的API。这就是为什么你找不到404的原因。404 表示没有您调用的 URL。
仔细检查你的休息模板,
restTemplate.getForEntity("http://api.nbp.pl/api/" + table+ "," +code+ Object.class, null, headers);
连接字符串时做错了。 它应该看起来像这样;
restTemplate.getForEntity("http://api.nbp.pl/api/exchangerates/rates/"+table+"/"+code, Object.class, null, headers);
对于 API 开发人员的提示,首先你应该使用 Postman 使用 api,然后使用 api 编写代码。
试试这个 - 我已经测试过了 - 它有效。请记住,这只是一个测试实现。方法main
内容必须复制到getAllCurriencyExchangeRates
方法中。 并且肯定会替换"a"
并通过变量"chf"
。我假设table
和code
是您想要使用的变量。我使用了String
因为我不知道您要返回哪种类型的对象。您可以肯定使用自己的pojo而不是String
。
package scripts;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
/**
* author: flohall
* date: 08.12.19
*/
public class Test {
public static void main(final String[] args){
final String url = "http://api.nbp.pl/api/exchangerates/rates";
final URI uri = UriComponentsBuilder.fromHttpUrl(url).path("/").path("a").path("/").path("chf").build().toUri();
System.out.println(uri);
final RestOperations restTemplate = new RestTemplate();
final ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
System.out.println(result.getBody());
}
}
试试这个
ResponseEntity<Object> response =
restTemplate.getForEntity("http://api.nbp.pl/api/exchangerates/rates/" + table + "/" + code, Object.class, headers);