Spring boot发送http请求

时间:2024-03-13 14:48:47
    @PostMapping("/request")
    @ResponseBody
    public Response1 request() {
        String authorizeUrl = "http://localhost:8080/user/response";
        Request1 request1=new Request1();
        request1.setGatewayId("id");
        request1.setGatewayPw("123456");
        request1.setRequestSn("sn");
        //发送Post数据并返回数据
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        //将请求头部和参数合成一个请求
        HttpEntity<Request1> requestEntity = new HttpEntity<>(request1, headers);
        //执行HTTP请求,将返回的结构使用ResultVO类格式化
        ResponseEntity<Response1> response = client.postForEntity(authorizeUrl, requestEntity, Response1.class);
        Response1 response1=response.getBody();
        return response1;
    }
    @RequestMapping("/response")
    @ResponseBody
    public Response1 response(@RequestBody Request1 request1) {
        String requestSn=request1.getRequestSn();
        Response1 response1 =new Response1();
        response1.setErrorCode(requestSn);
        return response1;
    }

Spring boot发送http请求