Spring Boot在内部调用另一个API时返回404。

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

Spring boot returns a 404 when calling another API internally

问题

I have a spring boot API that internally has to call another API and just "forward" the request.

private String APIRoot;
public APIInteractionController() {
    this.APIRoot = "<API root here, not showing it because it's private>";
}
//test if calling API works
@GetMapping("/test")
public String testAPI(){
    logCallAPI(APIRoot);
    String result = callAPI(APIRoot);
    return result;
}
private String callAPI(String uri){
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);
    return result;
}
private void logCallAPI(String uri){
    System.out.println("call API:\nuri: " + uri);
}

When I call the endpoint on my spring boot app, the logger statement gets outputted in the console, but in Postman, I just get a 404 even though when I call the API on itself it just returns "hello world" as the root just returns a test string.

Why is this, and how can I resolve this.

英文:

I have a spring boot API that internally has to call another API and just "forward" the request.

private String APIRoot;
public APIInteractionController() {
        this.APIRoot = &quot;&lt;API root here, not showing it because it&#39;s private&gt;&quot;;
    }
//test if calling API works
@GetMapping(&quot;/test&quot;)
public String testAPI(){
    logCallAPI(APIRoot);
    String result = callAPI(APIRoot);
    return result;
}
private String callAPI(String uri){
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);
    return result;
}
private void logCallAPI(String uri){
    System.out.println(&quot;call API:\nuri: &quot; + uri);
}

When I call the endpoint on my sprig boot app, the logger statement gets outputted in the console, but in postmane I just get a 404 even though when I call the API on itself it just returns "hello world" as the root just returns a test string.
Why is this, and how can I resolve this.

答案1

得分: 0

这个StackOverflow答案描述了如何为Spring RestTemplate启用HTTP wire日志记录。启用后,您应该能够在日志中看到实际调用的URL,从而找出为什么会收到404返回代码以及它是从哪里调用的。

英文:

This stackoverflow answer describes how to enable http wire logging for Spring RestTemplate. With this enabled, you should be able to see in your logs which URL is actually called and figure out from where, why you receive a 404 return code.

答案2

得分: 0

我通过在方法上添加 @ResponseBody 注解来解决了我在这里遇到的问题。

英文:

I solved the issue I was having here by adding the @ResponseBody annotation to the methods.

huangapple
  • 本文由 发表于 2023年3月31日 02:25:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891737.html
匿名

发表评论

匿名网友

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

确定