[英]Java Spring REST Get works just fine, but when posting json I get 404 error
[英]Java Spring error 404 while trying to get JSON from API. Works in postman
我正在嘗試從 API 獲取 JSON 對象,同時在標頭中使用 API 密鑰。 當我在 Postman 中測試它時,這非常有效,但是當我在我的 Spring 應用程序中嘗試它時。
我有一個錯誤:
出現意外錯誤(類型=未找到,狀態=404)。 沒有可用的消息。
API-Key 和URL
被替換為虛擬數據
@RequestMapping(value = "/apitest", method = RequestMethod.GET, headers ="APIKey=12345")
public @ResponseBody void testingAPI() throws ParseException {
final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("url", String.class);
System.out.println(response);
}
如果您在 Postman 中測試您的 API 並且它運行良好,而在您的應用程序中它不起作用,這意味着您的方法映射不正確或未正確調用.
但是從您說如果沒有 API 密鑰相同的配置有效的評論中,這意味着您的標頭未正確映射,在這種情況下,我建議使用@RequestHeader
注釋來處理您的 API 密鑰。
您的方法映射將是這樣的:
@RequestMapping(value = "/apitest", method = RequestMethod.GET)
public @ResponseBody void testingAPI(@RequestHeader("APIKey") String apiKey) throws ParseException {
final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("url", String.class);
System.out.println(response);
}
如果您想使用12345
作為 API 密鑰參數的默認值,您可以編寫:
@RequestMapping(value = "/apitest", method = RequestMethod.GET)
public @ResponseBody void testingAPI(@RequestHeader(name = "APIKey", defaultValue = "12345") String apiKey) throws ParseException {
您可以查看如何在 Spring REST 控制器教程中讀取 HTTP 標頭以進一步閱讀有關@RequestHeader
注釋的信息。
一個快速解決方法可能是將 void 更改為 Class。 喜歡
@RequestMapping(value = "/apitest", method = RequestMethod.GET, headers ="APIKey=12345")
@ResponseBody
public XXXResponse testingAPI() throws ParseException {
...
return new XXXRepsonse();
}
或者:
@RequestMapping(value = "/apitest", method = RequestMethod.GET, headers ="APIKey=12345")
public void testingAPI() throws ParseException {
...
}
您在請求中的哪里添加標頭? 您的控制器應如下所示:
@RestController
public class DemoController {
@GetMapping("/apitest" )
public void doRequest(@RequestHeader(name = "Ocp-Apim-Subscription-Key", defaultValue = "12345") String apiKey) {
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Ocp-Apim-Subscription-Key", apiKey);
ResponseEntity<String> responseEntity = restTemplate.exchange("https://api.kognif.ai/AIS/v1/aispositioncurrent?vesselimo=8505941&output=json",
HttpMethod.GET, new HttpEntity<String>(headers), String.class);
System.out.println(responseEntity.toString());
}
}
當然,指定有效的 Ocp-Apim-Subscription-Key
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.