有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SpringBoot如何向其他URL发送响应

我有以下代码:

@RequestMapping(
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
            path = "api/api1",
            method = RequestMethod.POST,
            produces = MediaType.ALL_VALUE
    )
    public ResponseEntity<?> api1CallBack(@RequestBody String requestBody, HttpServletRequest request) throws IOException, GeneralSecurityException, URISyntaxException {
       String response="{SOME_JSON}";
        URI callbackURL = new URI("http://otherAPIEnv/api2");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setLocation(callbackURL);
        return new ResponseEntity<String>(response,httpHeaders, HttpStatus.OK);
    }

我尝试了上面的代码,但是当我通过curl点击api1时,我在同一台机器上得到了响应,但是我希望响应被重定向到otherAPIEnv机器上的api2

有人能建议如何实现这种请求和响应吗


共 (4) 个答案

  1. # 1 楼答案

    您需要使用redirect并修改方法的返回类型

    public String api1CallBack(@RequestBody String requestBody, HttpServletRequest request) throws IOException {
           return "redirect:http://otherAPIEnv/api2";
    }
    
  2. # 2 楼答案

    看起来像是redirect的工作

    String redirectMe() {
        return "redirect:http://otherAPIEnv/api2"
    }
    

    至于卷曲。你有这个方法的POST映射,所以一定要用curl -X POST...或者把它改成GET

  3. # 3 楼答案

    When you send a request to a URL it should respond to the same otherwise client will be in waiting for it until it times out.

    因此,在这种情况下,方法应该有所不同

    首先,在主rest API中,必须发送响应代码来释放客户端

    然后,在API方法中,必须异步调用另一个方法,该方法调用api2并执行所需的操作

    下面是一个简单的例子

    @Autowired
    API2Caller api2Caller;
    
    @RequestMapping(
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
            path = "api/api1",
            method = RequestMethod.POST,
            produces = MediaType.ALL_VALUE
    )
    @ResponseStatus(HttpStatus.ACCEPTED)
    public void api1CallBack(@RequestBody String requestBody, HttpServletRequest request) throws IOException, GeneralSecurityException, URISyntaxException {
        api2Caller.callApi2(requestBody);
    }
    

    APICaller应该如下所示

    @Component
    public class API2Caller {
    
        @Async
        public SomeResultPojo callApi2() {
            // use RestTemplate to call the api2 
            return restTemplate.postForObject("http://otherAPIEnv/api2", request, SomeResultPojo.class);
        }
    }
    

    但您可以选择最舒适的方式来执行异步操作

  4. # 4 楼答案

    这是做这类事情的更模块化、更通用的方式:

    public @ResponseBody ClientResponse updateDocStatus(MyRequest myRequest) {
        ClientResponse clientResponse = new ClientResponse(CTConstants.FAILURE);
        try {
            HttpHeaders headers = prepareHeaders();
            ClientRequest request = prepareRequestData(myRequest);
            logger.info("cpa request is " + new Gson().toJson(request));
            HttpEntity<ClientRequest> entity = new HttpEntity<ClientRequest>(request, headers);
            String uri = cpaBaseUrl + updateDocUrl ;    
            ClientResponse serviceResponse = Utilities.sendHTTPRequest(uri, entity);
            clientResponse = serviceResponse;
            if (serviceResponse != null) {
                if (CTConstants.SUCCESS.equalsIgnoreCase(serviceResponse.getStatus())) {
                    clientResponse.setStatus(CTConstants.SUCCESS);
                    clientResponse.setMessage(" update success.");
                }
            }
        } catch (Exception e) {
            logger.error("exception occurred ", e);
            clientResponse.setStatus(CTConstants.ERROR);
            clientResponse.setMessage(e.getMessage());
        }
        return clientResponse;
    }
    
    
    
        public static ClientResponse sendHTTPRequest(String uri, HttpEntity<ClientRequest> entity) {
    
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
            SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
            rf.setReadTimeout(CTConstants.SERVICE_TIMEOUT);
            rf.setConnectTimeout(CTConstants.SERVICE_TIMEOUT);
    
            ParameterizedTypeReference<ClientResponse> ptr = new ParameterizedTypeReference<ClientResponse>() {
            };
            ResponseEntity<ClientResponse> postForObject = restTemplate.exchange(uri, HttpMethod.POST, entity, ptr);
            return postForObject.getBody();
    
        }