restTemplate发送post请求提交formdata


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public ResponseEntity download(@RequestParam MultipartFile file, @RequestParam Integer type) {
    File fileTemp = null;
  String url = http://127.0.0.1/api
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization","Bearer " + getToken());
        fileTemp = File.createTempFile("cw-", file.getOriginalFilename());
        file.transferTo(fileTemp);
 
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("type", type);
        multiValueMap.add("multipartFile", new FileSystemResource(fileTemp));
 
        HttpEntity<MultiValueMap<String, Object>> params = new HttpEntity<>(multiValueMap, headers);
        JSONObject response = restTemplate.postForObject(url, params, JSONObject.class);
 
        Integer code = response.getInteger("code");
        String msg = response.getString("msg");
        JSONObject data = null;
        if (code == 200) {
            data = response.getJSONObject("data");
        }
        Map map = new HashMap();
        map.put("data",data);
        map.put("code",code);
        map.put("msg",msg);
        return new ResponseEntity<>(map, HttpStatus.OK);
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if(fileTemp != null && fileTemp.exists()) {
            fileTemp.delete();
        }
    }
    Map map = new HashMap();
    map.put("code",500);
    map.put("token",null);
    map.put("msg","导入失败");
    return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);
}

  核心代码已标红

posted @   曹伟666  阅读(1101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示