欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java發(fā)送form-data請(qǐng)求實(shí)現(xiàn)文件上傳的示例代碼

 更新時(shí)間:2023年12月26日 11:16:08   作者:凌抆莂  
最近做一個(gè)需求,需要請(qǐng)求第三方接口上傳文件,該請(qǐng)求類(lèi)型是form-data請(qǐng)求,本文就來(lái)介紹一下java發(fā)送form-data請(qǐng)求實(shí)現(xiàn)文件上傳的示例代碼,感興趣的可以了解一下

一、業(yè)務(wù)需求:

需要請(qǐng)求第三方接口上傳文件,該請(qǐng)求類(lèi)型是form-data請(qǐng)求

二、postmant請(qǐng)求結(jié)果如下

三、maven依賴(lài):

        <!--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實(shí)現(xiàn)請(qǐng)求

    public static void test() {
        String goodsUrl = "http://0.0.0.0:7000/pangu/";
        //本地文件位置
        String fileName = "D:\\222.png";
        String str = null;
        try {
            //添加請(qǐng)求頭
            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請(qǐng)求提交form-data上傳文件
     *
     * @param url 上傳地址
     * @param headers 請(qǐng)求頭
     * @param file 上傳文件
     * @return
     */
    public static String doPostUploadFile(String 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();

        // 設(shè)置請(qǐng)求頭 boundary邊界不可重復(fù),重復(fù)會(huì)導(dǎo)致提交失敗
        String boundary = "-------------------------" + UUID.randomUUID().toString();
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

        // 創(chuàng)建MultipartEntityBuilder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 設(shè)置字符編碼
        builder.setCharset(StandardCharsets.UTF_8);
        // 模擬瀏覽器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // 設(shè)置邊界
        builder.setBoundary(boundary);
        // 設(shè)置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);
        CloseableHttpClient 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("對(duì)方響應(yīng)的狀態(tài)碼不在符合的范圍內(nèi)!");
                throw new RuntimeException();
            }
            return respContent;
        } catch (Exception e) {
            logger.error("網(wǎng)絡(luò)訪問(wèn)異常,請(qǐng)求url地址={},響應(yīng)體={},error={}", url, response, e);
            throw new RuntimeException();
        } finally {
            logger.info("統(tǒng)一外網(wǎng)請(qǐng)求參數(shù)打印,post請(qǐng)求url地址={},響應(yīng)={},耗時(shí)={}毫秒", url, respContent, (System.currentTimeMillis() - startTime));
            try {
                if (response != null) {
                    response.close();
                }
                if(null != httpClient){
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("請(qǐng)求鏈接釋放異常", e);
            }
        }
    }



    /**
     * 封裝請(qǐng)求頭
     *
     * @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.getValue());
            }
        }
    }

 注意:這里的builder.addPart("sendfile", new FileBody(file));,multipartFile對(duì)應(yīng)form表單的字段名稱(chēng)。

參考:Java發(fā)送form-data請(qǐng)求實(shí)現(xiàn)文件上傳_IceFloe_Rot的博客-CSDN博客

到此這篇關(guān)于java發(fā)送form-data請(qǐng)求實(shí)現(xiàn)文件上傳的示例代碼的文章就介紹到這了,更多相關(guān)java發(fā)送form-data請(qǐng)求上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級(jí)原理

    淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級(jí)原理

    這篇文章主要介紹了淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級(jí)原理,Hystrix 是 Netflix 的一款開(kāi)源的容錯(cuò)框架,通過(guò)服務(wù)隔離來(lái)避免由于依賴(lài)延遲、異常,引起資源耗盡導(dǎo)致系統(tǒng)不可用的解決方案,需要的朋友可以參考下
    2023-05-05
  • Spring Boot 2.0.0 終于正式發(fā)布-重大修訂版本

    Spring Boot 2.0.0 終于正式發(fā)布-重大修訂版本

    北京時(shí)間 2018 年 3 月 1 日早上,如約發(fā)布的 Spring Boot 2.0 在同步至 Maven 倉(cāng)庫(kù)時(shí)出現(xiàn)問(wèn)題,導(dǎo)致在 GitHub 上發(fā)布的 v2.0.0.RELEASE 被撤回
    2018-03-03
  • JAVA String.valueOf()方法的用法說(shuō)明

    JAVA String.valueOf()方法的用法說(shuō)明

    這篇文章主要介紹了JAVA String.valueOf()方法的用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-09-09
  • idea resources目錄下的application.properties不能自動(dòng)提示問(wèn)題

    idea resources目錄下的application.properties不能自動(dòng)提示問(wèn)題

    這篇文章主要介紹了idea resources目錄下的application.properties不能自動(dòng)提示問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • SpringBoot項(xiàng)目導(dǎo)入aliyun oss starter依賴(lài)后啟動(dòng)報(bào)錯(cuò)問(wèn)題

    SpringBoot項(xiàng)目導(dǎo)入aliyun oss starter依賴(lài)后啟動(dòng)報(bào)錯(cuò)問(wèn)題

    這篇文章主要介紹了SpringBoot項(xiàng)目導(dǎo)入aliyun oss starter依賴(lài)后啟動(dòng)報(bào)錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的方法

    MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的方法

    動(dòng)態(tài)SQL是MyBatis強(qiáng)大特性之一,極大的簡(jiǎn)化我們拼裝SQL的操作,本文主要介紹了MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-06-06
  • Java診斷工具Arthas的快速入門(mén)與實(shí)踐

    Java診斷工具Arthas的快速入門(mén)與實(shí)踐

    在Java開(kāi)發(fā)中,我們經(jīng)常會(huì)遇到各種性能問(wèn)題、內(nèi)存泄漏、線程阻塞等問(wèn)題,這些問(wèn)題往往難以通過(guò)常規(guī)的日志和監(jiān)控工具來(lái)定位和解決,Arthas作為一款開(kāi)源的Java診斷工具,提供了強(qiáng)大的實(shí)時(shí)監(jiān)控和診斷功能,本文將詳細(xì)介紹Arthas的安裝、基本使用以及一些常用命令
    2025-02-02
  • SpringBoot集成H2內(nèi)存數(shù)據(jù)庫(kù)的方法

    SpringBoot集成H2內(nèi)存數(shù)據(jù)庫(kù)的方法

    H2是Thomas Mueller提供的一個(gè)開(kāi)源的、純java實(shí)現(xiàn)的關(guān)系數(shù)據(jù)庫(kù)。本文主要介紹了SpringBoot集成H2內(nèi)存數(shù)據(jù)庫(kù),具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-09-09
  • Java 中如何使用 JavaFx 庫(kù)標(biāo)注文本顏色

    Java 中如何使用 JavaFx 庫(kù)標(biāo)注文本顏色

    這篇文章主要介紹了在 Java 中用 JavaFx 庫(kù)標(biāo)注文本顏色,在本文中,我們將了解如何更改標(biāo)簽的文本顏色,并且我們還將看到一個(gè)必要的示例和適當(dāng)?shù)慕忉專(zhuān)员愀菀桌斫庠撝黝},需要的朋友可以參考下
    2023-05-05
  • Springboot實(shí)現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并保存到本地

    Springboot實(shí)現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并保存到本地

    這篇文章主要為大家詳細(xì)介紹了Springboot實(shí)現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并將文件保存到本地效果的方法,文中的示例代講解詳細(xì),需要的可以參考一下
    2022-09-09

最新評(píng)論