Spring Boot 使用RestTemplate发送POST请求


不说废话,直接上一个笔者写的共通方法

    /**
     * post请求
     *
     * @param postUrl
     * @param param
     * @return java.lang.String
     * @author He
     * @date 2020/8/28 19:35
     **/
    public static <T> T post(String postUrl, Object param, Class<T> type) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        HttpHeaders headers = new HttpHeaders();
        // 设置验签用的数据
        // headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        // headers.add("Authorization", token);
        // 设置content-type,很据需求设置
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 设置请求体
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        String con = JSON.toJSONString(param);
        map.add("param", con);
        // 用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(postUrl, request, String.class);
        return JSON.parseObject(response.getBody(), type);
    }

HttpClient对接方式,可查看笔者的另一篇文章《HttpClient接口调用》


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM