当前位置: 代码网 > it编程>编程语言>Java > java发送post请求使用multipart/form-data格式文件数据到接口代码示例

java发送post请求使用multipart/form-data格式文件数据到接口代码示例

2024年12月22日 Java 我要评论
接口传输协议:http接口请求方式:post数据编码格式:utf-8数据传输格式:multipart/form-data需求:使用multipart/form-data格式传输文件到给定接口。工具类:

接口传输协议:http
接口请求方式:post
数据编码格式:utf-8
数据传输格式:multipart/form-data

需求:使用multipart/form-data格式传输文件到给定接口。

工具类:

import lombok.extern.slf4j.slf4j;
import org.apache.http.consts;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.client.config.requestconfig;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.methods.httprequestbase;
import org.apache.http.conn.ssl.noophostnameverifier;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
import org.apache.http.conn.ssl.truststrategy;
import org.apache.http.entity.contenttype;
import org.apache.http.entity.mime.httpmultipartmode;
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.httpclientbuilder;
import org.apache.http.ssl.sslcontextbuilder;
import org.apache.http.util.entityutils;

import javax.net.ssl.sslcontext;
import java.io.file;
import java.io.ioexception;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;
import java.util.hashmap;
import java.util.map;

/**
 * <p>
 *
 * @author 花鼠大师
 * @version :1.0
 * @date 2024/4/12 15:10
 */
@slf4j
public class sendfileutils {

    /**
     * 使用multipart/form-data方式传输文件
     * 发送文件方法
     * @param url 接口地址
     * @param file 文件
     */
    public static string sendmultipartfile(string url, file file) {
        //获取httpclient
        closeablehttpclient client = gethttpclient();
        httppost httppost = new httppost(url);
        fillmethod(httppost,system.currenttimemillis());

        // 请求参数配置
        requestconfig requestconfig = requestconfig.custom().setsockettimeout(60000).setconnecttimeout(60000)
                .setconnectionrequesttimeout(10000).build();
        httppost.setconfig(requestconfig);
        string res = "";
        string filename = file.getname();//文件名
        try {

            multipartentitybuilder builder = multipartentitybuilder.create();
            builder.setcharset(java.nio.charset.charset.forname("utf-8"));
            builder.setmode(httpmultipartmode.browser_compatible);

            /**
             * 假设有两个参数需要传输
             * 参数名:filaname 值 "文件名"
             * 参数名:file 值:file (该参数值为file对象)
             */
            //表单中普通参数
            builder.addpart("filaname ",new stringbody("来源", contenttype.create("text/plain", consts.utf_8)));
            
            // 表单中的文件参数 注意,builder.addbinarybody的第一个参数要写参数名
            builder.addbinarybody("file", file, contenttype.create("multipart/form-data",consts.utf_8), filename);

            httpentity entity = builder.build();
            httppost.setentity(entity);
            httpresponse response = client.execute(httppost);// 执行提交

            if (response.getstatusline().getstatuscode() == httpstatus.sc_ok) {
                // 返回响应结果
                res = entityutils.tostring(response.getentity(), java.nio.charset.charset.forname("utf-8"));
            }else {
                res = "响应失败";
                log.error("响应失败!");
            }
            return res;

        } catch (exception e) {
            e.printstacktrace();
            log.error("调用httppost失败!" + e.tostring());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (ioexception e) {
                    log.error("关闭httppost连接失败!");
                }
            }
        }
        log.info("数据传输成功!!!!!!!!!!!!!!!!!!!!");
        return res;
    }
    /**
     * 获取httpclient
     * @return
     */
    private static closeablehttpclient gethttpclient(){
        sslcontext sslcontext = null;
        try {
            sslcontext = new sslcontextbuilder().loadtrustmaterial(null, new truststrategy() {
           
                public boolean istrusted(x509certificate[] arg0, string arg1) throws certificateexception {
                    return true;
                }
            }).build();
        } catch (exception e) {
            e.printstacktrace();
            throw new runtimeexception(e);
        }
        sslconnectionsocketfactory sslconnectionsocketfactory = new sslconnectionsocketfactory(sslcontext,
                noophostnameverifier.instance);
        closeablehttpclient client = httpclientbuilder.create().setsslsocketfactory(sslconnectionsocketfactory).build();
        return client;
    }

    /**
     * 添加头文件信息
     * @param requestbase
     * @param timestamp
     */
    private static void fillmethod(httprequestbase requestbase, long timestamp){
        //此处为举例,需要添加哪些头部信息自行添加即可

        //设置时间戳,nginx,underscores_in_headers on;放到http配置里,否则nginx会忽略包含"_"的头信息
        requestbase.addheader("timestamp",string.valueof(timestamp));
        system.out.println(requestbase.getallheaders());
    }
}

所需依赖:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupid>org.apache.httpcomponents</groupid>
    <artifactid>httpclient</artifactid>
    <version>4.5.13</version>
</dependency>

总结 

到此这篇关于java发送post请求使用multipart/form-data格式文件数据到接口的文章就介绍到这了,更多相关java发送post请求文件数据到接口内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com