Java?Post請求發(fā)送form-data表單參數(shù)詳細(xì)示例代碼
Post請求發(fā)送form-data表單參數(shù)
一、pom文件引入依賴
<!-- 添加 Apache HttpClient 依賴 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 請使用最新的穩(wěn)定版本 -->
</dependency>
<!-- 如果你需要使用 MIME 相關(guān)的實(shí)用工具,添加 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> <!-- 請使用最新的版本號(hào) -->
</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());
// 請求參數(shù)配置
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);
/*
假設(shè)有兩個(gè)參數(shù)需要傳輸
參數(shù)名:filaName 值 "文件名"
參數(shù)名:file 值:file (該參數(shù)值為file對(duì)象)
*/
//表單中普通參數(shù)
builder.addPart("filaName ",new StringBody("來源", ContentType.create("text/plain", Consts.UTF_8)));
// 表單中的文件參數(shù) 注意,builder.addBinaryBody的第一個(gè)參數(shù)要寫參數(shù)名
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) {
// 返回響應(yīng)結(jié)果
res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}else {
res = "響應(yīng)失敗";
log.error("響應(yīng)失??!");
}
return res;
} catch (Exception e) {
e.printStackTrace();
log.error("調(diào)用HttpPost失敗!" + e);
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.error("關(guān)閉HttpPost連接失?。?);
}
}
}
log.info("數(shù)據(jù)傳輸成功!!!!!!!!!!!!!!!!!!!!");
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){
//此處為舉例,需要添加哪些頭部信息自行添加即可
//設(shè)置時(shí)間戳,nginx,underscores_in_headers on;放到http配置里,否則nginx會(huì)忽略包含"_"的頭信息
requestBase.addHeader("timestamp",String.valueOf(timestamp));
System.out.println(Arrays.toString(requestBase.getAllHeaders()));
}
}
總結(jié)
到此這篇關(guān)于Java Post請求發(fā)送form-data表單參數(shù)的文章就介紹到這了,更多相關(guān)Java Post請求發(fā)送form-data參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java線程之join_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
join() 定義在Thread.java中,下文通過源碼分享join(),需要的朋友參考下吧2017-05-05
maven中springboot-maven-plugin的5種打包方式
本文主要介紹了maven中springboot-maven-plugin的5種打包方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-09-09
SpringBoot Caffeine+Redisson配置二級(jí)緩存實(shí)踐
文章介紹了兩級(jí)緩存架構(gòu)的必要性,詳細(xì)描述了使用Redission進(jìn)行SpringBoot緩存整合的方法,包括配置本地緩存、設(shè)置過期時(shí)間、開啟緩存功能、解決key相同cacheNames不同的問題以及修改自定義緩存管理器等內(nèi)容2026-05-05
Java中構(gòu)造方法set/get和toString的使用詳解
這篇文章主要介紹了Java中構(gòu)造方法set/get和toString的使用詳解,構(gòu)造函數(shù)的最大作用就是創(chuàng)建對(duì)象時(shí)完成初始化,當(dāng)我們在new一個(gè)對(duì)象并傳入?yún)?shù)的時(shí)候,會(huì)自動(dòng)調(diào)用構(gòu)造函數(shù)并完成參數(shù)的初始化,需要的朋友可以參考下2019-07-07
java中Supplier知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于java中Supplier知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-04-04
Springboot發(fā)送post請求的幾種方式總結(jié)
這篇文章主要為大家詳細(xì)介紹了Springboot發(fā)送post請求的幾種方式,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定的幫助,感興趣的小伙伴可以了解一下2024-01-01

