有这么一个业务场景: 系统A 把文件传送到 系统B。 系统B对文件进行处理(加水印or保存...)系系统B 把处理完的文件返回给系统A 。 系统A进行保存备份。
编写了两个类 sendFile(系统A) ReceiveFileController(系统B)采用 httpClient 进行接口调用 ,系统B 把回传的文件写在 response的流里。话不多说,上代码
系统A:
POM文件
org.apache.httpcomponents httpmime 4.5 org.apache.httpcomponents httpclient 4.5
调用接口 发送文件 接收返回的文件流保存文件
package com.example.File;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.entity.ContentType;import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import java.io.*;import java.nio.file.Files;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;public class sendFile { public static void main(String[] args) { doPostFile2("https://.../receiveFile/test","userid",new File("D:\\1.jpg"),"D:\\2.jpg"); } public static void doPostFile2(String url, String param, File file,String downloadPath) { CloseableHttpClient httpClient = HttpClients.createDefault(); // https 需要SSL if (url.startsWith("https://")) { httpClient = sslClient(); } String resultString = ""; CloseableHttpResponse response = null; HttpPost httppost = new HttpPost(url); //返回的字节流 byte[] bytes = null; try { // HttpMultipartMode.RFC6532 避免文件名为中文时乱码 MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); builder.setCharset(Consts.UTF_8); builder.setContentType(ContentType.MULTIPART_FORM_DATA); //或者使用字节流也行,根据具体需要使用 builder.addBinaryBody("file", Files.readAllBytes(file.toPath()),ContentType.APPLICATION_OCTET_STREAM,file.getName()); // 添加参数 addTextBody的key可以自定义和被调接口的入参保持一直 可多个addTextBody key不一样即可 需在接收方接收 builder.addTextBody("param", param); //builder.addTextBody("key1", param); //可以设置 请求头 //httppost.addHeader("token", param.get("token")); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); // 设置超时时间 httppost.setConfig(getConfig()); response = httpClient.execute(httppost); //我这里 调用接口返的字节流 所以获取字节数组 //resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); HttpEntity entity = response.getEntity(); //输出流 字节数组 bytes = EntityUtils.toByteArray(entity); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } InputStream inputStream = new ByteArrayInputStream(bytes); OutputStream outputStream = null; try { // todo下载的目录不存在需要创建 byte[] bs = new byte[1024]; int len; outputStream = new FileOutputStream(downloadPath); while ((len = inputStream.read(bs)) != -1) { outputStream.write(bs, 0, len); } } catch (Exception e) { throw new RuntimeException("照片处理失败:" + e); } finally { try { outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } //超时时间; private static RequestConfig getConfig() { return RequestConfig.custom().setConnectionRequestTimeout(50000).setSocketTimeout(150000) .setConnectTimeout(50000).build(); } private static CloseableHttpClient sslClient() { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } }}
系统B
package com.example.File;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;@RestController@RequestMapping(value = "/receiveFile")public class ReceiveFileController { @PostMapping("/test") public void receiveFile(@RequestParam("file")MultipartFile file, @RequestParam("param")String param, HttpServletResponse response){ try { //拿到文件流 InputStream inputStream = file.getInputStream(); //todo开始处理业务 //处理完的文件放在 response中 OutputStream outputStream = response.getOutputStream(); //todo 把处理的东西写在 outputStream即可 } catch (IOException e) { e.printStackTrace(); } }}
来源地址:https://blog.csdn.net/weixin_45177751/article/details/129861591