欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

十分钟学会 RestTemplate 的简单使用

程序员文章站 2022-06-02 15:41:56
...

你知道的越多,你不知道的越多
点赞再看,养成习惯
如果您有疑问或者见解,或者没有积分想获取项目,欢迎指教:
企鹅:869192208

前言

本篇主要记录工作上遇到的 RestTemplate 的基本使用,它是 Spring 提供的用来访问 Rest 服务的客户端,RestTmplate 提供了很多便捷的方法,可以大大提供开发效率。

一、不带参数的默认 headers 的 Get 请求

String url = "http://ip:port/testGetMethod";
String str = restTemplate.getForObject(url , String.class);

二、带参数的默认 headers 的 Get 请求

String url = "http://ip:port/testGetMethod/{talk}/{name}"; 
//或者testGetMethod/{1}/{2} {里面的参数无所谓,只是根据下面的Object... uriVariables 逐一绑定到上面{} 中去的}
String str = restTemplate.getForObject(url , String.class,"hello" , "johnny");

或者

String url = "http://ip:port/testGetMethod/{talk}/{name}";
Map<String,String> map = new HashMap<>(); 
map.put("talk" , "hello"); 
map.put("name" , "johnny"); 
String str = restTemplate.getForObject(url , String.class,map); 

三、带参数的 Get 下载文件请求(下载 pdf 文件为例,参数直接拼接到 url)

public ResponseEntity<byte[]> requestSendDownloadFile(String url){
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());

        List list = new ArrayList<>();
        list.add(MediaType.valueOf("application/pdf"));
        headers.setAccept(list);

        headers = gap(headers);

        HttpEntity<byte[]> entity = new HttpEntity<>(headers);
        ResponseEntity<byte[]> rsp = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                byte[].class);

        log.info("文件下载请求结果状态码:" + rsp.getStatusCode());
        log.info("文件下载请求结果文件名:" + rsp.getHeaders().getContentDisposition().getFilename());
        log.info("文件下载请求结果内容:" + rsp.getBody());
        return rsp;
    }

参考:https://blog.csdn.net/u013979547/article/details/52665655

四、带参数的 Post 请求

public ResponseEntity<Object> requestSend(String url, Map<String, String> requestParm) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());

        headers = gap(headers);

        MultiValueMap<String, Object> requestParmMap =new LinkedMultiValueMap<>();
        //循环转换
        Iterator it =requestParm.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            requestParmMap.add(entry.getKey(), entry.getValue());
        }

        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(requestParmMap, headers);
        log.info("url:" + url + ",httpEntity:" + JSON.toJSONString(httpEntity));
        return restTemplate.postForEntity(url, httpEntity, Object.class);
    }

五、发起整段 json 参数的 Post 请求

public ResponseEntity<Object> requestSendPost(String url, Map<String, Object> requestParm) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());

        headers = gap(headers);

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(requestParm, headers);

        log.info("url:" + url + ",httpEntity:" + JSON.toJSONString(httpEntity));
        return restTemplate.postForEntity(url, httpEntity, Object.class);
    }

附录:

补充上面示例代码中处理 headers 部分的 gap 方法

public HttpHeaders gap(HttpHeaders headers){
        log.info("into intercept ,paasid = {},paastoken = {}",passId,passToken);
        // 加入自定义字段
        ZoneOffset zoneOffset=ZoneOffset.ofHours(8);
        //初始化LocalDateTime对象
        LocalDateTime localDateTime=LocalDateTime.now();
        //获取LocalDateTime对象对应时区的Unix时间戳
        long x_tif_timeStamp = localDateTime.toEpochSecond(zoneOffset);
        String x_tif_nonce = UUID.randomUUID().toString();
        String plain = x_tif_timeStamp + passToken + x_tif_nonce + x_tif_timeStamp;
        log.info("into intercept ,plain = {}",plain);
        String x_tif_signature = encrypt(plain,"SHA-256");
        headers.add("x-tif-paasid", passId);
        headers.add("x-tif-signature", x_tif_signature);
        headers.add("x-tif-timestamp", Long.toString(x_tif_timeStamp));
        headers.add("x-tif-nonce", x_tif_nonce);
        return headers;
 	/**
     * 软摘要算法
     *
     * @param plain 需要摘要的数据
     * @return base64摘要的值
     */
    public static String sm3(String plain) {
        byte[] md = new byte[32];
        byte[] psw = null;
        try {
            psw = plain.getBytes("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        SM3Digest sm3 = new SM3Digest();
        sm3.update(psw, 0, psw.length);
        sm3.doFinal(md, 0);
        System.out.println(Hex.toHexString(md));
        return Base64.getEncoder().encodeToString(md);
    }

    private static String encrypt(String inputText, String algorithmName)
    {
        if (inputText == null || "".equals(inputText.trim()))
        {
            throw new IllegalArgumentException("请输入要加密的内容");
        }
        if (algorithmName == null || "".equals(algorithmName.trim()))
        {
            algorithmName = "md5";
        }
        String encryptText = null;
        try
        {
            MessageDigest m = MessageDigest.getInstance(algorithmName);
            m.update(inputText.getBytes("UTF8"));
            byte s[] = m.digest();
            // m.digest(inputText.getBytes("UTF8"));
            return hex(s);
        } catch (Exception e){

        }
        return encryptText;
    }

    /**
     * 返回十六进制字符串
     *
     * @param arr
     * @return
     */
    private static String hex(byte[] arr)
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ++i)
        {
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }
    }