Java发送Http请求之——文件的发送

本文详细介绍如何使用Java实现文件的上传与接收功能,包括POM依赖配置、发送文件请求的工具类代码、验证测试接口及文件保存方法,解决数据传输过程中的中文乱码问题。

1.POM依赖

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

2.发送文件请求工具类

package com.example.demo.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class HttpUtil {

    public static String sendFileReq(String url, MultipartEntityBuilder multipartEntityBuilder, String encoding) throws IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost (url);

        //设置请求参数
        HttpEntity httpEntity = multipartEntityBuilder.build();

        httpPost.setEntity(httpEntity);

        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public static void main(String[] args) {
        String url = "http://localhost:8080/receivePostReq";

        File attach_file = new File("D:/1/a.png");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setContentType(ContentType.MULTIPART_FORM_DATA);

        builder.addBinaryBody("attach_file",attach_file);

//        ContentType contentType = ContentType.create("text/plain","utf-8");
        ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), StandardCharsets.UTF_8);
        StringBody stringBody = new StringBody("发送文件",contentType);

        builder.addPart("userName",stringBody);
        try {
            String result1 = sendFileReq (url, builder, "utf-8");
            System.out.println (result1);

        } catch (Exception e) {
            e.printStackTrace ( );
        }
    }

}

3.验证测试接口

package com.example.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;

@RestController
public class DemoController {

    @PostMapping("/receivePostReq")
    public String receivePostReq(
            @RequestParam(value = "userName") String userName,
            @RequestParam(value = "attach_file") MultipartFile[] attach_file,
            HttpServletRequest request
    ){
        System.out.println("userName="+userName);

        //这里file可以接受前台的文件,可以是一个,也可以是多个,这正是MultipartFile强大的地方。
        String filePath = "D:\\1";
        String fileName[]=new String[attach_file.length];

        if (attach_file != null && attach_file.length > 0) {
            //判断使用有文件上传
            for (int i = 0; i < attach_file.length; i++) {
                //循环上传(多文件上传)
                try {
                    Calendar cale = null;
                    cale = Calendar.getInstance();
                    int year = cale.get(Calendar.YEAR);	int month = cale.get(Calendar.MONTH) + 1;
                    int day = cale.get(Calendar.DATE);
                    //给图片重命名加上日期前缀
//                    filePath= request.getSession().getServletContext().getRealPath("/") ;
                    //获取服务器img文件夹地址(这里指的是local:8080/项目名/img)
                    fileName[i]= "/img/" + year + ""+ month + "" + day + "_" + attach_file[i].getOriginalFilename();
                    //重命名图片。
                    String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
                    //截取文件后缀判断是否是一张图片
                    if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
                        int length = attach_file[i].getBytes().length;
                        if (!((length / 1000) > 5120)) {
                            //判断图片地址
                            System.out.println("图片"+i+"="+fileName[i]);
                            //将图片输出到制定的文件夹目录中
                            attach_file[i].transferTo(new File(filePath,fileName[i]));
                        }else{
                            System.out.println("图片过大");
                        }
                    }else{
                        System.out.println("只能上传图片啊亲!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("上传失败");
                }
            }
        } else {
            System.out.println("请选择文件");
        }

        return "请求成功";
    }

}

4.总结

以上,Java后台发送文件,接收文件就完成了。

文件保存参考

数据传输中文乱码解决参考

### Java 发送 HTTP 请求并加密文件Java发送HTTP请求的同时对文件进行加密涉及多个方面,包括但不限于创建HTTP客户端、准备要传输的数据以及实现加密逻辑。下面提供一种基于`HttpURLConnection`的方式来进行POST请求,并利用AES算法来加密文件内容。 #### 使用 `HttpURLConnection` 进行 POST 请求 为了发起带有附件上传功能的 HTTPS POST 请求,在构建 multipart/form-data 类型的消息体之前先读取本地磁盘上的目标文件作为输入流。接着通过设置合适的 Content-Type 和其他必要的头部字段告知服务器即将接收的内容形式[^1]。 ```java import java.io.*; import javax.net.ssl.HttpsURLConnection; // ... other imports ... public void sendEncryptedFile(String urlStr, File fileToUpload) throws Exception { URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); // Set up connection properties. conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); try(OutputStream outputStream = conn.getOutputStream()){ writeMultipartData(outputStream, encryptFile(fileToUpload)); int responseCode = conn.getResponseCode(); System.out.println("Response Code : " + responseCode); } } ``` #### AES 加密方法 对于敏感信息如文件内容而言,可以采用高级加密标准(AES),这是一种广泛接受的安全编码方案。此部分展示了如何定义一个简单的函数用于执行给定路径下文件对象的实际加密过程[^2]。 ```java private byte[] encryptFile(File inputFile) throws IOException{ Cipher cipher = null; SecretKeySpec secretKey = generateSecretKey(); try { cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // ECB模式仅作示例用途;实际应用建议使用更安全的CBC或GCM模式 cipher.init(Cipher.ENCRYPT_MODE, secretKey); } catch (NoSuchAlgorithmException | NoSuchPaddingException e){ throw new RuntimeException(e.getMessage()); } FileInputStream inputStream = new FileInputStream(inputFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8 * 1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byte[] encryptedBytes = cipher.update(buffer, 0, bytesRead); if (encryptedBytes != null) baos.write(encryptedBytes); } byte[] finalEncryptedBytes = cipher.doFinal(); if(finalEncryptedBytes!=null)baos.write(finalEncryptedBytes); return baos.toByteArray(); } private static SecretKeySpec generateSecretKey(){ KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); // Use appropriate key size as per your requirement and compliance requirements SecretKey secretKey = keyGen.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), "AES"); }catch(Exception ex){ throw new RuntimeException(ex.getMessage()); } } ``` 上述代码片段实现了基本的功能需求——即向指定URL地址提交经过AES加密处理后的二进制数据包。需要注意的是,这里简化了一些细节(比如错误处理),因此在生产环境中应当更加严谨地对待安全性考量和异常情况管理等问题[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值