spring boot 用RestTemplate post 在服务器间传送文件

 

不同公司间传数据是件麻烦的事情,协商格式会搞死人。主机厂会利用EDI。低成本而可靠的方式是己方系统导出excel文档,发送;对方接收,导入对方系统。看似麻烦,实际上前期协调和后期升级都会很简单。
为了可靠,不能直接发到对方系统上,而是先注册个网站,租个服务器,将excel发到服务器上。对方去服务器上取文件。

本地服务器上传到远程服务器

		// 上传文件		
		FileSystemResource fileSystemResource = new FileSystemResource(fileNameWithPath);
		if (!fileSystemResource.exists()) {//文件不存在处理		
		}
		MediaType type = MediaType.parseMediaType("multipart/form-data");
		headers.setContentType(type);
		//headers.set("Cookie", cookies);//session用于验证身份
		MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
		form.add("file", fileSystemResource);
		//form.add("pass", finalpass);;//用于验证身份		
		HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
		responseEntity = restTemplate.postForEntity(urlTransfer, files, String.class);//发送
		//此处要添加错误处理	
		String result = responseEntity.getBody().toString();

从远程服务器下载到本地服务器

		HttpHeaders headers = new HttpHeaders();
		HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
		ResponseEntity<byte[]> response = restTemplate.exchange(getFilePath, HttpMethod.GET, httpEntity, byte[].class);

		if (response.getStatusCodeValue() != 200) {//异常处理
		
		}
		//写入本地
		try {
			File file = new File(path + File.separator + fileName);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(response.getBody());
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
原文地址:https://www.cnblogs.com/zhangrui153169/p/11730507.html