接口间传输文件流(二)
在接口间传输文件流中,介绍了通过HttpURLConnection完成文件流的传输,下面来看文件流传输的另一种实现,基于RestTemplate完成文件流的传输。
1、pom依赖
同接口间传输文件流。
2、实现工具类
2.1、报文数据转换工具
1 import org.apache.commons.lang3.StringUtils; 2 import javax.xml.bind.JAXBContext; 3 import javax.xml.bind.Marshaller; 4 import javax.xml.bind.Unmarshaller; 5 import java.io.StringReader; 6 import java.io.StringWriter; 7 import java.nio.charset.StandardCharsets; 8 9 public class XmlUtil { 10 11 /** 12 * 实体类转XML 13 * @param object 14 * @return 15 */ 16 public static String convertToXml(Object object) { 17 StringWriter sw = new StringWriter(); 18 try { 19 JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); 20 Marshaller marshaller = jaxbContext.createMarshaller(); 21 // 编码格式 22 marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8); 23 // 是否格式化生成的xml 24 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 25 // 是否省略头信息 26 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false); 27 28 marshaller.marshal(object, sw); 29 }catch (Exception ex) { 30 ex.printStackTrace(); 31 } 32 return sw.toString().replace("standalone=\"yes\"", StringUtils.EMPTY); 33 } 34 35 /** 36 * xml转实体 37 * @param clazz 38 * @param xml 39 * @return 40 */ 41 public static Object convertXmlToObj(Class clazz, String xml) { 42 Object xmlObj = null; 43 try { 44 JAXBContext jaxbContext = JAXBContext.newInstance(clazz); 45 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 46 StringReader sr = new StringReader(xml); 47 xmlObj = unmarshaller.unmarshal(sr); 48 } catch (Exception ex) { 49 ex.printStackTrace(); 50 } 51 return xmlObj; 52 } 53 54 /** 55 * 获取xml某个标签的元素值 56 * @param xml 57 * @param tag 58 * @return 59 */ 60 public static String getEleVal(String xml, String tag) { 61 String res = StringUtils.EMPTY; 62 if (StringUtils.isBlank(xml)) { 63 return res; 64 } 65 String tagStr = "<".concat(tag).concat(">"); 66 String tagEnd = "</".concat(tag).concat(">"); 67 int tagStrIndex = xml.indexOf(tagStr); 68 int tagEndIndex = xml.indexOf(tagEnd); 69 if (tagStrIndex == -1 || tagEndIndex == -1) { 70 return res; 71 } 72 try { 73 res = xml.substring(tagStrIndex + tagStr.length(), tagEndIndex); 74 }catch (Exception ex) { 75 ex.printStackTrace(); 76 } 77 return res; 78 } 79 80 }
2.2、数据传输工具
1 import org.springframework.beans.factory.annotation.Autowired; 2 import org.springframework.boot.web.client.RestTemplateBuilder; 3 import org.springframework.core.io.Resource; 4 import org.springframework.http.HttpEntity; 5 import org.springframework.http.HttpHeaders; 6 import org.springframework.http.MediaType; 7 import org.springframework.stereotype.Component; 8 import org.springframework.web.client.RestTemplate; 9 10 @Component 11 public class HttpUtil { 12 13 @Autowired 14 private RestTemplateBuilder restTemplateBuilder; 15 16 /** 17 * 接收字符串响应报文 18 * @param body 19 * @param url 20 * @return 21 */ 22 public String postXml(String body, String url){ 23 HttpHeaders headers = new HttpHeaders(); 24 headers.setContentType(MediaType.APPLICATION_XML); 25 HttpEntity<String> entity = new HttpEntity<>(body, headers); 26 RestTemplate templacte = restTemplateBuilder.build(); 27 String res = templacte.postForObject(url, entity, String.class); 28 return res; 29 } 30 31 /** 32 * 接收文件流 33 * @param body 34 * @param url 35 * @return 36 */ 37 public Resource postXml2(String body, String url){ 38 HttpHeaders headers = new HttpHeaders(); 39 headers.setContentType(MediaType.APPLICATION_XML); 40 HttpEntity<String> entity = new HttpEntity<>(body, headers); 41 RestTemplate templacte = restTemplateBuilder.build(); 42 Resource resource = templacte.postForObject(url, entity, Resource.class); 43 return resource; 44 } 45 46 }
3、Controller控制模拟系统交互
1 import com.snails.util.HttpUtil; 2 import com.snails.util.XmlUtil; 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.core.io.Resource; 5 import org.springframework.web.bind.annotation.RequestBody; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RestController; 8 import javax.servlet.ServletOutputStream; 9 import javax.servlet.http.HttpServletResponse; 10 import java.io.*; 11 import java.util.Objects; 12 13 @RestController 14 public class DownloadBillController { 15 @Autowired 16 HttpUtil httpUtil; 17 18 /** 19 * 前置服务的实现 20 * 前置服务接收获取文件请求 21 * @param reqMsg 22 * @param response 23 */ 24 @RequestMapping("/front/down") 25 public void downloadFile(@RequestBody String reqMsg, HttpServletResponse response) { 26 String reqUrl = "http://127.0.0.1:8085/down"; 27 Resource resource = httpUtil.postXml2(reqMsg, reqUrl); 28 InputStream inputStream = null; 29 ServletOutputStream outputStream = null; 30 try{ 31 inputStream = resource.getInputStream(); 32 System.out.println("服务端返回文件接收流大小 len=" + inputStream.available()); 33 // 返回内容的MIME类型 34 response.setContentType("application/form-data"); 35 //设置响应头中文件的下载方式为附件方式,以及设置文件名 36 response.addHeader("Content-Disposition", "attachment; filename=" + "target.tar.gz"); 37 outputStream = response.getOutputStream(); 38 byte[] buffer = new byte[1024]; 39 int len; 40 outputStream = response.getOutputStream(); 41 while ((len = inputStream.read(buffer)) != -1) { 42 outputStream.write(buffer, 0, len); 43 outputStream.flush(); 44 } 45 }catch (Exception ex){ 46 ex.printStackTrace(); 47 }finally { 48 try { 49 if (Objects.nonNull(inputStream)) { 50 inputStream.close(); 51 } 52 if (Objects.nonNull(outputStream)) { 53 outputStream.close(); 54 } 55 } catch (IOException e) { 56 e.printStackTrace(); 57 } 58 } 59 } 60 61 /** 62 * 应用服务的实现 63 * 应用服务获取文件 64 * @param reqMsg 65 * @param response 66 */ 67 @RequestMapping("/down") 68 public void file(@RequestBody String reqMsg, HttpServletResponse response) { 69 String str = "D:\\source.tar.gz"; 70 FileInputStream fis = null; 71 ServletOutputStream outputStream = null; 72 try { 73 String accNo = XmlUtil.getEleVal(reqMsg, "AccNo"); 74 if (!"1234556".equals(accNo)) { 75 throw new Exception("交易失败!"); 76 } 77 fis = new FileInputStream(str); 78 byte[] buffer = new byte[1024]; 79 int len; 80 outputStream = response.getOutputStream(); 81 while ((len = fis.read(buffer)) != -1) { 82 outputStream.write(buffer, 0, len); 83 outputStream.flush(); 84 } 85 } catch (Exception ex){ 86 ex.printStackTrace(); 87 }finally { 88 try { 89 if (Objects.nonNull(fis)) { 90 fis.close(); 91 } 92 if (Objects.nonNull(outputStream)) { 93 outputStream.close(); 94 } 95 } catch (IOException e) { 96 e.printStackTrace(); 97 } 98 } 99 } 100 }
4、测试
4.1、在D盘准备好压缩文件 source.tar.gz
文件详情如下:
4.2、postman请求前置服务下载文件
4.2.1、请求的测试报文
<?xml version="1.0" encoding="UTF-8"?><root><head><ReqTime>20230630154339</ReqTime></head><body><AccNo>1234556</AccNo></body></root>
4.2.2、请求详情
发送请求并下载文件:
保存文件:
4.3、查看下载文件
下载文件详情如下:
至此,基于RestTemplate完成文件流的传输介绍完毕。