java使用RestTemplate调用远端接口

1.环境:springBoot+mybatisPlus+oracle

/**
     * 调用远端接口
     * @param serverUrl:远端接口地址
     * @param json:map文件转成字符串
     * @param filePath:上传有文件时,填写文件地址,如无问价上传,传null
     * @return
     */
    public static ResponseEntity  rstTemplate (String serverUrl,String json,String filePath){
        RestTemplate restTemplate = new RestTemplate();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //设置请求体,注意是LinkedMultiValueMap
        MultiValueMap form = new LinkedMultiValueMap<>();
        //此处用于上传文件,若无文件上传,则写入null
        if(StringUtils.hasLength(filePath)) {
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            form.add("file", fileSystemResource);
        }
        form.add("parameterJson",json);

        //用HttpEntity封装整个请求报文
        HttpEntity> httpEntity = new HttpEntity(form, headers);

        ResponseEntity s = restTemplate.postForEntity(serverUrl,httpEntity, String.class);
        return s;
    }

2调用方法

public static void main(String[] args){
Map mapZip=new HashMap<>();
  mapZip.put("fileName",“测试文件.txt”);
            String jsonMap=JSON.toJSONString(mapZip);
            //调接口
            String fileZipUrl="http://localhost:8080/uploadProject/fileService/departMentZip";
            String iniPath="d:/test/测试文件.txt"
            //将详情json发送到文件服务器,返回详情json地址与计费模块zip地址
            ResponseEntity responseEntity=FileUpLoadUtil.test(fileZipUrl,jsonMap,iniPath);
   }

详细
https://mp.csdn.net/mdeditor/99713503#

你可能感兴趣的:(java)