Java?Post請求發(fā)送form-data表單參數詳細示例代碼
更新時間:2025年07月05日 09:23:47 作者:胡德祿a
POST請求是一種常見的網絡通信操作,用于向服務器發(fā)送數據,這種請求通常用于上傳文件或者提交包含大量數據的表單,這篇文章主要介紹了Java?Post請求發(fā)送form-data表單參數的相關資料,需要的朋友可以參考下
Post請求發(fā)送form-data表單參數
一、pom文件引入依賴
<!-- 添加 Apache HttpClient 依賴 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 請使用最新的穩(wěn)定版本 -->
</dependency>
<!-- 如果你需要使用 MIME 相關的實用工具,添加 mime4j 依賴 -->
<dependency>
<groupId>org.apache.james</groupId>
<artifactId>apache-mime4j</artifactId>
<version>0.6.1</version> <!-- 請使用最新的穩(wěn)定版本 -->
</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方式傳輸文件
* 發(fā)送文件方法
* @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);// 執(zhí)行提交
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請求發(fā)送form-data表單參數的文章就介紹到這了,更多相關Java Post請求發(fā)送form-data參數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
Java String 和 new String()的比較與區(qū)別
這篇文章主要介紹了Java String 和 new String()的區(qū)別的相關資料,需要的朋友可以參考下2017-04-04
Java使用Optional實現優(yōu)雅避免空指針異常
空指針異常(NullPointerException)可以說是Java程序員最容易遇到的問題了。為了解決這個問題,Java?8?版本中推出了?Optional?類,本文就來講講如何使用Optional實現優(yōu)雅避免空指針異常吧2023-03-03
如何使用Springfox?Swagger實現API自動生成單元測試
Springfox是一個使用Java語言開發(fā)開源的API Doc的框架,它的前身是swagger-springmvc,可以將我們的Controller中的方法以文檔的形式展現,這篇文章主要介紹了如何使用Springfox?Swagger實現API自動生成單元測試,感興趣的朋友跟隨小編一起看看吧2024-04-04
spring aop之@AfterReturning不生效問題及解決
這篇文章主要介紹了spring aop之@AfterReturning不生效問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

