JAVA 接口文件传参 & 接收文件; 接口接收文件流(主打的就是无脑)

有这么一个业务场景: 系统A 把文件传送到 系统B 系统B对文件进行处理(加水印or保存...)系系统B 把处理完的文件返回给系统A 系统A进行保存备份。

编写了两个类  sendFile(系统A)  ReceiveFileController(系统B)采用 httpClient 进行接口调用 ,系统B 把回传的文件写在 response的流里。话不多说,上代码

系统A:

1.POM文件

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>

2. 调用接口 发送文件 接收返回的文件流保存文件

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;

/**
 * @Cimpany yuJ.wang
 * @ClassName: sendFile
 * @Description: 发送文件
 * @Date: 2023/3/30 16:24
 * @Author: 老王头
 */
public class sendFile {


    public static void main(String[] args) {
        doPostFile2("https://.../receiveFile/test","userid",new File("D:\\1.jpg"),"D:\\2.jpg");
    }

    /**
    * @Description:   httpClient调用接口传送文件  接收文件流保存本地
    * * @Param url:  接口地址
     * @Param param: 参数值
     * @Param file: 文件
     * @Param downloadPath: 保存地址
    * @return: void
    * @Author: laoWangTou
    * @Date: 2023/3/30
    */
    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();
    }

    /**
     * HTTPS   设置SSL请求处理
     */
    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;

/**
 * @Cimpany yuJ.wang
 * @ClassName: receiveFile
 * @Description: 接收文件
 * @Date: 2023/3/30 16:24
 * @Author: 老王头
 */
@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();
        }

    }

}

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值