json 如何在Sping Boot 应用程序中使用或调用另一个Rest API?

ma8fv8wu  于 2022-11-26  发布在  其他
关注(0)|答案(3)|浏览(127)

我正在尝试在我的Sping Boot 应用程序中调用外部Rest API端点。我有一个API密钥,是我在将其用于我的Rest应用程序之前生成的。每当我尝试点击GET请求时,都会显示缺少API密钥403禁止错误

org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: "{"error":"Missing API key"}"
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:109)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:168)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:361)
    at com.rakhi.restapidemo.controller.CloudHealthAccessController.getCloudHealthReports(CloudHealthAccessController.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:670)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:750)

我试着写这段代码来得到想要的输出。不幸的是无法做到。

@RequestMapping(value = {"/reports"}, method = {RequestMethod.GET, RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Object> getCloudHealthReports(){
        logger.info("Inside get cloud health reporting function..!!!!");
        try {
            String apiKey = "abc-xyz-example-apikey-e215d82537ba";
            final String uri = "https://chapi.cloudhealthtech.com/olap_reports";
            RestTemplate restTemplate = new RestTemplate();
            
            URL url = new URL(uri);
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            
            http.setRequestProperty("Accept", "application/json");
            http.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", apiKey));
            
            ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
            
            return new ResponseEntity<>(response.getHeaders(), HttpStatus.OK);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return new ResponseEntity<>("Error! Please try again later", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
jecbmhm3

jecbmhm31#

HttpURLConnection c = (HttpURLConnection) new URL("https://chapi.cloudhealthtech.com/olap_reports").openConnection();
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("Authorization", "Bearer abc-xyz-example-apikey-e215d82537ba");
try {
  System.out.println(c.getResponseCode() + ": " + new String(c.getInputStream().readAllBytes()));
} catch(Exception e) {
  System.out.println(c.getResponseCode() + ": " + new String(c.getErrorStream().readAllBytes()));
}

我得到:

403: {"error":"Unrecognized API key"}

这比“缺少”API键要好。也许可以尝试使用这个示例,一次改变一件事。
看看这个:Sending GET request with Authentication headers using restTemplate
您需要以特定于Spring的方式传递请求头。

8wtpewkr

8wtpewkr2#

您确定您为其余呼叫提供了正确的标题吗?
有一件事是可以的,那就是你的API会回答你,所以它工作正常,但不是很好。
如果可以的话,你可能也应该检查你的响应API中的日志。

ApiClient apiClient = new ApiClient();
apiClient.setBasePath("BASE_URL");
apiClient.setApiKeyPrefix("App");
apiClient.setApiKey("API_KEY");
return apiClient;
k10s72fa

k10s72fa3#

我试过这种方法,得到了预期的结果。

public ResponseEntity<Object> getCloudHealthReports() throws IOException{
        ResponseEntity<String> responseEntity = null;
        try {
            final String uri = "https://chapi.cloudhealthtech.com/olap_reports";
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer API-KEY");
            
            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            
            String response = responseEntity.getBody();
            
            return new ResponseEntity<Object>(response, HttpStatus.OK);
            
        } catch (Exception e) {
            e.printStackTrace();
            
            return new ResponseEntity<Object>("Please try again later", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

相关问题