HttpClient模拟表单提交上传文件

 需求:如何利用HttpClient,发起post请求,模拟表单提交,在后端上传文件?

上传文件接口:

    /**
     * 文件上传测试接口
     * @return
     */
    @PostMapping("/upload")
    public Object uploadFileTest(@RequestParam("file") MultipartFile file, @RequestParam("file_name") String file_name, @RequestParam("file_code") String file_code) {
        System.out.println(file_name+","+file_code);
        return "OK";
    }

启动后,可以通过postman进行调用,最后打印OK,表示接口可以调用通

然后就是正式编码环节了

首先引入需要的包:

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

 编写main方法,直接发起调用

 public static String httpClientUploadFile(String url, File file) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        //每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
        String boundary = "--------------4585696313564699";
        try {
            //文件名
            String fileName = file.getName();
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+boundary);

            //HttpEntity builder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //字符编码
            builder.setCharset(Charset.forName("UTF-8"));
            //模拟浏览器
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            //boundary
            builder.setBoundary(boundary);
            //multipart/form-data
            builder.addPart("file", new FileBody(file, ContentType.DEFAULT_BINARY));
            // binary
            //builder.addBinaryBody("name=\"file\"; filename=\"mysql.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            //其他参数
            //builder.addTextBody("file_name", fileName, ContentType.create("text/plain", Consts.UTF_8));
            builder.addTextBody("file_name", fileName, ContentType.MULTIPART_FORM_DATA);
            builder.addTextBody("file_code", "111111", ContentType.MULTIPART_FORM_DATA);
            //HttpEntity
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);
            //响应
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("result" + result);
        return result;
    }

    //main 方法
    public static void main(String[] args) {
        httpClientUploadFile("http://127.0.0.1:8080/test/tempA/upload",new File("e:/tmp/mysql.docx"));
    }

最后返回OK,调用成功

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值