RestTemplate常用方式

RestTemplate常用方式

1.Get

1.带请求头

@GetMapping("test00")
public DTO test00(HttpServletRequest request) {
    System.out.println(request.getHeaderNames());
    DTO dto = new DTO();
    dto.setStr("123");
    dto.setList(Arrays.asList("1", "2"));
    return dto;
}
@Test
public void test00() {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("token", "Bearer 10001");
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(headers);
    ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange("http://localhost:8080/test00", HttpMethod.GET, entity, ResponseDTO.class);
    System.out.println(responseEntity.getBody());
}

2.Restful

@GetMapping("test01")
public DTO test01(@RequestParam(name = "name", required = false) String name,
                  @RequestParam(name = "age", required = false) Integer age) {
    System.out.println(name + ", " + age);
    DTO dto = new DTO();
    dto.setStr("123");
    dto.setList(Arrays.asList("1", "2"));
    return dto;
}
@Test
public void test01() {
    RestTemplate restTemplate = new RestTemplate();
    Map<String, Object> map = new HashMap<>();
    //接口参数
    map.put("name","xiaoming01");
    map.put("age",9);
    ResponseEntity<ResponseDTO> responseEntity = restTemplate.getForEntity("http://localhost:8080/test01?name={name}&age={age}", ResponseDTO.class, map);
    System.out.println(responseEntity.getBody());
}

3.占位符

@GetMapping("test02/{name}/{age}")
public DTO test02(@PathVariable(name = "name", required = false) String name,
                  @PathVariable(name = "age", required = false) Integer age) {
    System.out.println(name + ", " + age);
    DTO dto = new DTO();
    dto.setStr("123");
    dto.setList(Arrays.asList("1", "2"));
    return dto;
}
@Test
public void test02() {
    RestTemplate restTemplate = new RestTemplate();
    Map<String, Object> map = new HashMap<>();
    //接口参数
    map.put("name","xiaoming02");
    map.put("age",9);
    ResponseEntity<ResponseDTO> responseEntity = restTemplate.getForEntity("http://localhost:8080/test02/{name}/{age}", ResponseDTO.class, map);
    System.out.println(responseEntity.getBody());
}

2.Post

1.表单

@PostMapping("test10")
public DTO test10(@RequestParam(name = "name", required = false) String name,
                   @RequestParam(name = "age", required = false) Integer age) {
    System.out.println(name + ", " + age);
    DTO dto = new DTO();
    dto.setStr("123");
    dto.setList(Arrays.asList("1", "2"));
    return dto;
}
@Test
public void test10() {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    //接口参数
    map.add("name","xiaoming");
    map.add("age",9);
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
    ResponseEntity<ResponseDTO> responseEntity = restTemplate.postForEntity("http://localhost:8080/test10", entity, ResponseDTO.class);
    System.out.println(responseEntity.getBody());
}

2.Json

@Data
static class Person {
    String name;
    Integer age;
}

@PostMapping("test11")
public DTO test11(@RequestBody Person person) {
    System.out.println(person.getName() + ", " + person.getAge());
    DTO dto = new DTO();
    dto.setStr("123");
    dto.setList(Arrays.asList("1", "2"));
    return dto;
}
@Test
public void test11() throws JSONException {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    // 如果有相应对象, 创建对象也可
    JSONObject param = new JSONObject();
    param.put("name", "xiaoming");
    param.put("age", 9);
    HttpEntity<String> entity = new HttpEntity<>(param.toString(), headers);
    ResponseEntity<ResponseDTO> responseEntity = restTemplate.postForEntity("http://localhost:8080/test11", entity, ResponseDTO.class);
    System.out.println(responseEntity.getBody());
}

3.上传下载

1.上传

@PostMapping("test20")
public DTO test20(@RequestParam("file") MultipartFile file,
                           @RequestParam("filename") String filename) {
    File folder = new File("C:\\Users\\DELL\\Desktop\\test");
    if (!folder.isDirectory()) {
        folder.mkdirs();
    }

    try {
        // 文件保存
        file.transferTo(new File(folder, filename + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."))));
    } catch (IOException e) {
        e.printStackTrace();
    }

    DTO dto = new DTO();
    dto.setStr("123");
    dto.setList(Arrays.asList("1", "2"));
    return dto;
}
@Test
public void test20(){
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
    param.add("file", new FileSystemResource(new File("C:\\Users\\DELL\\Desktop\\image\\image-20220808224258982.png")));
    param.add("filename", "test");
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(param, headers);

    ResponseEntity<ResponseDTO> responseEntity = restTemplate.postForEntity("http://localhost:8080/test20", request, ResponseDTO.class);
    System.out.println(responseEntity.getBody());
}

2.下载

@GetMapping(value = "test21")
public void test21(@RequestParam(value = "filename") String filename,
                         HttpServletRequest request,
                         HttpServletResponse response) throws Exception {

    File file = new File("E:\\download" + File.separator + filename);
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(file);
        String extendFileName = filename.substring(filename.lastIndexOf('.'));
        // 动态设置响应类型,根据前台传递文件类型设置响应类型
        response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
        // 设置响应头,attachment表示以附件的形式下载,inline表示在线打开
        response.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(filename,"UTF-8"));
        // 获取输出流对象(用于写文件)
        OutputStream os = response.getOutputStream();
        // 下载文件,使用spring框架中的FileCopyUtils工具
        FileCopyUtils.copy(fis,os);
    }
}
/**
 * 将文件一次性读取到内存后, 再进行写盘, 遇到大文件时可能会 OOM
 * @throws IOException
 */
@Test
public void test21() throws IOException {
    RestTemplate restTemplate = new RestTemplate();
    String filename = "test.zip";

    //发起请求,直接返回对象(restful风格)
    ResponseEntity<byte[]> rsp = restTemplate.getForEntity("http://localhost:8080/test21?filename={filename}", byte[].class, filename);
    System.out.println("文件下载请求结果状态码:" + rsp.getStatusCode());

    // 将下载下来的文件内容保存到本地
    String targetPath = "C:\\Users\\DELL\\Desktop\\test" + File.separator + filename;
    Files.write(Paths.get(targetPath), Objects.requireNonNull(rsp.getBody(), "未获取到下载文件"));
}
/**
 * 使用流式处理, 有多少写多少, 避免一次性读取到内存后造成 OOM
 */
@Test
public void test22() {
    RestTemplate restTemplate = new RestTemplate();
    String filename = "test.zip";

    // APPLICATION_OCTET_STREAM,表示以流的形式进行数据加载
    RequestCallback requestCallback = request -> request.getHeaders()
            .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

    String targetPath = "C:\\Users\\DELL\\Desktop\\test" + File.separator + filename;
    // 流式处理, 拿到一部分数据就写一部分数据, 而不是将所有数据拿到内存后再进行写盘
    restTemplate.execute("http://localhost:8080/test21?filename={filename}", HttpMethod.GET, requestCallback, clientHttpResponse -> {
        Files.copy(clientHttpResponse.getBody(), Paths.get(targetPath));
        return null;
    }, filename);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值