使用 RestTemplate 请求接口下载文件: https://blog.csdn.net/weixin_44953227/article/details/124683295
上传代码
如果是本地文件可以使用这个方法
FileSystemResource resource = new FileSystemResource("文件路径");
@RestController
@RequestMapping("/test")
public class TestUploadController {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RestTemplate restTemplate;
@PostMapping("/upload")
public Object getGdDzyzApiService(@RequestParam("file") MultipartFile file) {
Resource resource = file.getResource();
// 获取本地文件资源
// FileSystemResource resource = new FileSystemResource("home/java/test.pdf");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
// 设置文件
param.add("file", resource);
HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(param, httpHeaders);
String url = "https://blog.csdn.net/upload/file";
logger.info(">>> 上传文件url: {}", url);
try {
URI uri = new URI(url);
ResponseEntity<Map> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, Map.class);
logger.warn(">>> responseEntity: {}", responseEntity);
if (responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
logger.error(">>> 状态码异常: {}", responseEntity.getStatusCodeValue());
throw new RuntimeException(String.format("状态码异常 %s", responseEntity.getStatusCodeValue()));
}
Map body = responseEntity.getBody();
if (body == null) {
throw BusinessException.withErrorMsg("返回结果为空");
}
return body;
} catch (Exception e) {
e.printStackTrace();
}
return "上传失败";
}
}