Java Spring error 404 while trying to get JSON from API. Works in postman

imkepo :

I am trying to get a JSON Object from an API while using an API key in the header. This works perfectly when I test it in Postman, but when I try it in my Spring application.

I got an error:

There was an unexpected error (type=Not Found, status=404). No message available.

API-Key and the URL are changed out with dummy data

@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);
}
cнŝdk :

If your are testing your API in Postman and it works perfectly, and in your application it's not working, this means that your method mapping isn't correct or it's not correctly called.

But from the comments where you said that the same configuration works if you don't have an API key, this means that your header isn't correctly mapped, in this case I'd recommend using @RequestHeader annotation to handle your API key.

Your method mapping will be like this:

@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);
}

If you want to use 12345 as a default value for your API key param you can write:

@RequestMapping(value = "/apitest", method = RequestMethod.GET)
public @ResponseBody void testingAPI(@RequestHeader(name = "APIKey", defaultValue = "12345") String apiKey) throws ParseException {

You can check How to Read HTTP Headers in Spring REST Controllers tutorial for further reading about the @RequestHeader annotation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=136107&siteId=1