RestTemplate发送请求封装

1.每次项目发送http请求要写一堆参数拼接,返回值解析逻辑,看起来很乱,所以封装统一的请求方式
上代码:

/**
 * http请求service
 *
 * @author: cxp
 * @date: 2021/6/17 11:18
 */
@Slf4j
@Component
public class HttpService {

    @Resource
    private RestTemplate restTemplate;

    /**
     * get请求
     *
     * @param: url 请求地址
     * @param: headers 请求头
     * @param: params 参数
     * @param: responseType 返回值类型
     * @return: 请求返回值
     * @author: cxp
     * @date: 2021/6/17 11:22
     */
    public <T> T getRequest(String url, Map<String, String> headers, Map<String, Object> params, Class<T> responseType) {
        this.judgeParams(url, responseType);
        HttpHeaders httpHeaders = this.packHeaders(headers, MediaType.APPLICATION_JSON);
        StringBuilder urlSb = new StringBuilder(url);
        if (params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                urlSb.append("&").append(param.getKey()).append("=").append(param.getValue());
            }
        }
        url = urlSb.toString().replaceFirst("&", "?");
        log.info("url: {}", url);
        log.info("headers: {}", httpHeaders.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, responseType);
        log.info("response: {}", responseEntity.getBody());
        return responseEntity.getBody();
    }

    /**
     * post(json)请求
     *
     * @param: url 请求地址
     * @param: headers 请求头
     * @param: params 参数
     * @param: responseType 返回值类型
     * @return: 请求返回值
     * @author: cxp
     * @date: 2021/6/17 11:22
     */
    public <T> T postRequest(String url, Map<String, String> headers, Map<String, Object> params, Class<T> responseType) {
        this.judgeParams(url, responseType);
        HttpHeaders httpHeaders = this.packHeaders(headers, MediaType.APPLICATION_JSON);
        if (params == null) {
            params = new HashMap<>();
        }
        log.info("url: {}", url);
        log.info("headers: {}", httpHeaders.toString());
        log.info("params: {}", params.toString());
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, httpHeaders);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, requestEntity, responseType);
        log.info("response: {}", responseEntity.getBody());
        return responseEntity.getBody();
    }

    /**
     * post表单请求
     *
     * @param: url 请求地址
     * @param: headers 请求头
     * @param: params 参数
     * @param: responseType 返回值类型
     * @return: 请求返回值
     * @author: cxp
     * @date: 2021/6/17 11:22
     */
    public <T> T postForm(String url, Map<String, String> headers, Map<String, Object> params, Class<T> responseType) {
        this.judgeParams(url, responseType);
        HttpHeaders httpHeaders = this.packHeaders(headers, MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<>();
        if (params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                paramsMap.add(param.getKey(), param.getValue());
            }
        }
        log.info("url: {}", url);
        log.info("headers: {}", httpHeaders.toString());
        log.info("params: {}", paramsMap.toString());
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(paramsMap, httpHeaders);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, requestEntity, responseType);
        log.info("response: {}", responseEntity.getBody());
        return responseEntity.getBody();
    }

    /**
     * 校验参数
     *
     * @param url          请求地址
     * @param responseType 返回值类型
     */
    private <T> void judgeParams(String url, Class<T> responseType) {
        if (url == null || url.trim().equals("")) {
            throw new BusinessException("url不能为空");
        }
        if (responseType == null) {
            throw new BusinessException("返回值类型不能为空");
        }
    }

    /**
     * 包装headers
     *
     * @param headers   请求头内容
     * @param mediaType 请求头类型
     * @return 请求头
     */
    private HttpHeaders packHeaders(Map<String, String> headers, MediaType mediaType) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(mediaType);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpHeaders.add(header.getKey(), header.getValue());
            }
        }
        return httpHeaders;
    }

测试用例:

    @GetMapping("/getTest")
    public ResultData getTest(String a, Integer b) {
        log.info("a = {}", a);
        log.info("b = {}", b);
        return ResultData.success();
    }

    @PostMapping("/postTest")
    public ResultData postTest(@RequestBody Map<String, Object> map) {
        log.info("a = {}", map.get("a"));
        log.info("b = {}", map.get("b"));
        return ResultData.success();
    }

    @PostMapping("/postForm")
    public ResultData postForm(String a, Integer b) {
        log.info("a = {}", a);
        log.info("b = {}", b);
        return ResultData.success();
    }

    @GetMapping("/httpTest")
    public ResultData httpTest() {
        String url = "http://localhost:8080/demo/getTest";
        Map<String, String> headers = new HashMap<>();
        headers.put("test", "cxp");
        Map<String, Object> params = new HashMap<>();
        params.put("a", "hello");
        params.put("b", 1);
        ResultData resultData = httpService.getRequest(url, headers, params, ResultData.class);
        log.info("get: {}", JSONUtil.toJsonStr(resultData));
        url = "http://localhost:8080/demo/postTest";
        resultData = httpService.postRequest(url, headers, params, ResultData.class);
        log.info("post: {}", JSONUtil.toJsonStr(resultData));
        url = "http://localhost:8080/demo/postForm";
        resultData = httpService.postForm(url, headers, params, ResultData.class);
        log.info("postForm: {}", JSONUtil.toJsonStr(resultData));
        return ResultData.success();
    }

测试请求:
执行操作
结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值