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();
        }

    }

}

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java多线程处理HTTP接口接收文件可以使用Java的内置类库和第三方库来实现。下面是一个简单的示例代码: ```java import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class HttpFileReceiver { private static final int PORT = 8080; // 监听端口号 public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(PORT); System.out.println("Server started, listening on port " + PORT); while (true) { Socket socket = serverSocket.accept(); // 创建一个新的线程来处理每个客户端请求 new Thread(() -> { try { InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = reader.readLine(); String[] tokens = line.split(" "); String method = tokens[0]; String path = tokens[1]; // 处理HTTP POST请求 if (method.equals("POST")) { String boundary = ""; int contentLength = 0; while ((line = reader.readLine()) != null) { if (line.startsWith("Content-Type: multipart/form-data; boundary=")) { boundary = line.substring(line.indexOf("=") + 1); } else if (line.startsWith("Content-Length: ")) { contentLength = Integer.parseInt(line.substring(line.indexOf(":") + 1).trim()); } else if (line.trim().equals("")) { break; } } // 读取文件内容 byte[] buffer = new byte[4096]; int bytesRead = 0; int totalBytesRead = 0; boolean boundaryFound = false; while (totalBytesRead < contentLength && (bytesRead = inputStream.read(buffer)) != -1) { totalBytesRead += bytesRead; // 查找分隔符 for (int i = 0; i < bytesRead; i++) { if (buffer[i] == boundary.charAt(0)) { // 检查是否找到分隔符 boundaryFound = true; for (int j = 1; j < boundary.length(); j++) { if (buffer[i + j] != boundary.charAt(j)) { boundaryFound = false; break; } } if (boundaryFound) { break; } } } // 写入文件 if (!boundaryFound) { // TODO: 将文件内容写入到磁盘上 // 每个线程需要处理自己的文件 } } } // 发送响应 OutputStream outputStream = socket.getOutputStream(); String response = "HTTP/1.1 200 OK\r\n\r\n"; outputStream.write(response.getBytes()); outputStream.flush(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }).start(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们首先创建一个ServerSocket对象来监听指定的端口,然后在while循环中不断接收客户端连接。每当有一个客户端连接进来时,就创建一个新的线程来处理它。 在处理HTTP POST请求时,我们需要解析HTTP头部,查找Content-Type、Content-Length和分隔符等信息。然后,我们可以使用InputStream来读取文件内容,并将文件内容写入到磁盘上。 最后,我们需要发送一个HTTP响应,告诉客户端文件已经接收成功。 注意:上面的代码仅作为示例,实际使用时需要根据具体的需求进行修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值