开发者

java发送form-data请求实现文件上传的示例代码

开发者 https://www.devze.com 2023-12-28 10:22 出处:网络 作者: 凌抆莂
目录一、业务需求:二、postmant请求结果如下三、maven依赖:四、Java实现请求一、业务需求:
目录
  • 一、业务需求:
  • 二、postmant请求结果如下
  • 三、maven依赖:
  • 四、Java实现请求

一、业务需求:

需要请求第三方接口上传文件,该请求类型是form-data请求

二、postmant请求结果如下

java发送form-data请求实现文件上传的示例代码

三、maven依赖:

        <!--http-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.12</version>
        </dependency>

四、java实现请求

    public static void test() {
        String goodsUrl = "http://0.0.0.0:7000/pangu/";
        //本地文件位置
        String fileName = "D:\\222.png";
        String str = null;
        try {
            //添加请求头
            HashMap<String, String> map = new HashMap<>();
            //map.put("token", CommonConstant.token);
            File file = new File(fileName);
            str = doPostUploadFile(goodsUrl + "/sacw/CommonConfig/uploadFile", map, file);
            if(file.exists()) {
                //boolean delete = file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * post请求提交form-data上传文件
     *
     * @param url 上传地址
     * @param headers 请求头
     * @param file 上传文件
     * @return
     */
    public static String doPostUploadFile(Stringphp url, Map<String, String> headers, File file) {
        HttpPost httpPost = new HttpPost(url);
        packageHeader(headers, httpPost);
        String fileName = file.getName();

        CloseableHttpResponse response = null;

        String respContent = null;

        long startTime = System.currentTimeMillis();

        // 设置请求头 boundary边界不可重复,重复会导致提交失败
        String boundary = "-------------------------" + UUID.randomUUID().toString();
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

        // 创建MultipartEntityBuilder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 设置字符编码
        builder.setCharset(StandardCharsets.UTF_8);
        // 模拟浏览器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // 设置边界
        builder.setBoundary(boundary);
        // 设置multipart/form-data流文件
        builder.addPart("sendfile", new FileBody(file));
        builder.addTextBody("fileType", "1");
        // application/octet-stream代表不知道是什么格式的文件
        builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName);

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        CloseableHttandroidpClient httpClient = HttpClients.createDefault();
        try {
            response = httpClient.execute(httpPost);
            if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() < 400) {
                HttpEntity he = response.getEntity();
                if (he != null) {
                    respContent = EntityUtils.toString(he, "UTF-8");
                }
            } else {
                logger.error("对方响应的状态码不在符合的范围内!");
                throw new RuntimeException();
            }
            return respContent;
        } catch (Exception e) {
            logger.error("网络访问异常,请求url地址={},响应体={},error={}", url, response, e);
            throw new RuntimeException();
        } finally javascript{
            logger.info("统一外网请求参数打印,post请求url地址={},响应={},耗时=js{}毫秒", url, respContent, (System.currentTimeMillis() - startTime));
            try {
                if (response != null) {
                    response.close();
                }
                if(null != httpClient){
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("请求链接释放异常", e);
            }
        }
    }



    /**
     * 封装请求头
     *
     * @param paramsHeads
     * @param httpMethod
     */
    private static void packageHeader(Map<String, String> paramsHeads, HttpRequestBase httpMethod) {
        if (null!= paramsHeads && paramsHeads.size()>0) {
            Set<Map.Entry<String, String>> entrySet = paramsHeads.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                httpMethod.setHeader(entry.getKey(), entry.g编程etValue());
            }
        }
    }

 注意:这里的builder.addPart("sendfile", new FileBody(file));multipartFile对应form表单的字段名称。

参考:Java发送form-data请求实现文件上传_IceFloe_Rot的博客-CSDN博客

到此这篇关于java发送form-data请求实现文件上传的示例代码的文章就介绍到这了,更多相关java发送form-data请求上传内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号