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

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后台发送文件,接收文件就完成了。

文件保存参考

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值