HttpClient实现表单提交上传文件

 更新时间:2022年8月14日 15:54  点击:311 作者:小明同学12138

本文实例为大家分享了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,调用成功

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/qq_28534469/article/details/120327851

[!--infotagslink--]

相关文章