SpringBoot RestTemplate使用工具类

·  阅读 875

1.常用方法

public class RestTemplateUtil {

    private static final String EMPTY_STR = "";

    /**
     * get请求
     * @param restTemplate
     * @param url
     * @param headerMap
     * @param paramMap
     * @return
     */
    public static String get(RestTemplate restTemplate, String url, Map<String,String> headerMap, Map<String,String> paramMap){
        HttpHeaders headers = new HttpHeaders();
        if(!CollectionUtils.isEmpty(headerMap)){
            headerMap.forEach((k,v)-> headers.set(k,v));
        }
        StringBuffer paramStr = new StringBuffer(EMPTY_STR);
        if(!CollectionUtils.isEmpty(paramMap)){
            paramMap.forEach((k,v)->{
                if(paramStr.toString().equals(EMPTY_STR)){
                    paramStr.append("?").append(k).append("=").append(v);
                }else{
                    paramStr.append("&").append(k).append("=").append(v);
                }
            });
        }
        HttpEntity<String> httpEntity = restTemplate.exchange(url+paramStr.toString(), HttpMethod.GET,CollectionUtils.isEmpty(headerMap) ? null : new HttpEntity<>(headers),String.class);
        return httpEntity.getBody();
    }

    /**
     * post JSON
     * @param restTemplate
     * @param url
     * @param headerMap
     * @param paramObjectStr
     * @return
     */
    public static String postJson(RestTemplate restTemplate, String url, Map<String,String> headerMap, String paramObjectStr){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        if(!CollectionUtils.isEmpty(headerMap)){
            headerMap.forEach((k,v)-> headers.set(k,v));
        }
        String resultStr = restTemplate.postForObject(url,new HttpEntity<>(paramObjectStr,headers),String.class);
        return resultStr;
    }

    /**
     * post Form
     * @param restTemplate
     * @param url
     * @param headerMap
     * @param paramMap
     * @return
     */
    public static String postForm(RestTemplate restTemplate, String url, Map<String,String> headerMap, MultiValueMap<String,Object> paramMap){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if(!CollectionUtils.isEmpty(headerMap)){
            headerMap.forEach((k,v)-> headers.set(k,v));
        }
        String resultStr = restTemplate.postForObject(url,new HttpEntity<>(paramMap,headers),String.class);
        return resultStr;
    }
}
复制代码

1.1测试用例

@Test
    public void tt01(){
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("id","2");
        String resultStr = RestTemplateUtil.get(restTemplate,"http://127.0.0.1:8080/user/getById",null,paramMap);
        System.out.println(resultStr);
    }

    @Test
    public void tt02(){
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String,Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("id","2");
        String resultStr = RestTemplateUtil.postForm(restTemplate,"http://127.0.0.1:8080/user/getById",null,paramMap);
        System.out.println(resultStr);
    }

    @Test
    public void tt03(){
        RestTemplate restTemplate = new RestTemplate();
        User user = new User();
        user.setUserName("xxxx");
        user.setPwd("1231231132");
        String resultStr = RestTemplateUtil.postJson(restTemplate,"http://127.0.0.1:8080/user/add",null, JSON.toJSONString(user));
        ResponseMessage<User> responseMessage = JSON.parseObject(resultStr,new TypeReference<ResponseMessage<User>>(){});
        System.out.println(responseMessage.getData());
    }
复制代码

2.文件相关用法

二、上传文件
MultiValueMap<String, Object> multiPartBody = new LinkedMultiValueMap<>();  
multiPartBody.add("file", new ClassPathResource("/tmp/user.txt"));  
RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity  
        .post(uri)  
        .contentType(MediaType.MULTIPART_FORM_DATA)  
        .body(multiPartBody);  

三、下载文件
// 小文件  
RequestEntity requestEntity = RequestEntity.get(uri).build();  
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(requestEntity, byte[].class);  
byte[] downloadContent = responseEntity.getBody();  
  
// 大文件  
ResponseExtractor<ResponseEntity<File>> responseExtractor = new ResponseExtractor<ResponseEntity<File>>() {  
    @Override  
    public ResponseEntity<File> extractData(ClientHttpResponse response) throws IOException {  
        File rcvFile = File.createTempFile("rcvFile", "zip");  
        FileCopyUtils.copy(response.getBody(), new FileOutputStream(rcvFile));  
        return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(rcvFile);  
    }  
};  
File getFile = this.restTemplate.execute(targetUri, HttpMethod.GET, null, responseExtractor); 
复制代码
分类:
后端
标签: