Java模拟formdata发送请求-文件上传

public String upload() {
        //HttpHeaders httpHeaders = RestTemplateUtils.basicAuthenticationInfo(poAuthConfig.getUsername(), poAuthConfig.getPassword());
        //上传的地址
        String url = "请求接口地址";
        String filePath = "文件路径地址";
        RestTemplate rest = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders() {
            {
                String auth = "用户admin" + ":" + "密码123456";
                byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
                String authHeader = "Basic " + new String(encodedAuth);
                set("Authorization", authHeader);
                set("Content-Type", "multipart/form-data");
            }
        };

        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        //MultipartFile的名称
        param.add("file", resource);
        param.add("name", "test_template");
        param.add("fileName", "test_template.xlsx");
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, httpHeaders);
        ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
        String result = responseEntity.getBody();
        System.out.println(result);
        return result;
    }


版权声明:本文为weixin_42870215原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。