Java Post请求发送form-data表单参数详细示例代码
更新时间:2025年07月05日 09:23:47 作者:胡德禄a
POST请求是一种常见的网络通信操作,用于向服务器发送数据,这种请求通常用于上传文件或者提交包含大量数据的表单,这篇文章主要介绍了Java Post请求发送form-data表单参数的相关资料,需要的朋友可以参考下
Post请求发送form-data表单参数
一、pom文件引入依赖
<!-- 添加 Apache HttpClient 依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 请使用最新的稳定版本 -->
</dependency>
<!-- 如果你需要使用 MIME 相关的实用工具,添加 mime4j 依赖 -->
<dependency>
<groupId>org.apache.james</groupId>
<artifactId>apache-mime4j</artifactId>
<version>0.6.1</version> <!-- 请使用最新的稳定版本 -->
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version> <!-- 请使用最新的版本号 -->
</dependency>
二、工具类
package com.hn.bdzzhixun.utils;
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.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @author lzn
* @version :1.0
* 2024/11/22 15:10
*/
@Slf4j
public class SendFileUtils {
/**
* 使用multipart/form-data方式传输文件
* 发送文件方法
* @param url 接口地址
* @param file 文件
*/
public static String sendMultipartFile(String url, File file,String dwbh) {
//获取HttpClient
CloseableHttpClient client = getHttpClient();
HttpPost httpPost = new HttpPost(url);
fillMethod(httpPost,System.currentTimeMillis());
// 请求参数配置
RequestConfig requestConfig = RequestConfig
.custom()
.setSocketTimeout(60000)
.setConnectTimeout(3000)
.setConnectionRequestTimeout(3000)
.build();
httpPost.setConfig(requestConfig);
String res = "";
String fileName = file.getName();//文件名
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.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);
builder.addTextBody("positionId",dwbh);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);// 执行提交
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回响应结果
res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}else {
res = "响应失败";
log.error("响应失败!");
}
return res;
} catch (Exception e) {
e.printStackTrace();
log.error("调用HttpPost失败!" + e);
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.error("关闭HttpPost连接失败!");
}
}
}
log.info("数据传输成功!!!!!!!!!!!!!!!!!!!!");
return res;
}
/**
* 获取HttpClient
*/
private static CloseableHttpClient getHttpClient(){
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
return HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
/**
* 添加头文件信息
*/
private static void fillMethod(HttpRequestBase requestBase, long timestamp){
//此处为举例,需要添加哪些头部信息自行添加即可
//设置时间戳,nginx,underscores_in_headers on;放到http配置里,否则nginx会忽略包含"_"的头信息
requestBase.addHeader("timestamp",String.valueOf(timestamp));
System.out.println(Arrays.toString(requestBase.getAllHeaders()));
}
}
总结
到此这篇关于Java Post请求发送form-data表单参数的文章就介绍到这了,更多相关Java Post请求发送form-data参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
相关文章
maven中springboot-maven-plugin的5种打包方式
本文主要介绍了maven中springboot-maven-plugin的5种打包方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-09-09
SpringBoot Caffeine+Redisson配置二级缓存实践
文章介绍了两级缓存架构的必要性,详细描述了使用Redission进行SpringBoot缓存整合的方法,包括配置本地缓存、设置过期时间、开启缓存功能、解决key相同cacheNames不同的问题以及修改自定义缓存管理器等内容2026-05-05
Java中构造方法set/get和toString的使用详解
这篇文章主要介绍了Java中构造方法set/get和toString的使用详解,构造函数的最大作用就是创建对象时完成初始化,当我们在new一个对象并传入参数的时候,会自动调用构造函数并完成参数的初始化,需要的朋友可以参考下2019-07-07


最新评论