java發(fā)送post請(qǐng)求使用multipart/form-data格式文件數(shù)據(jù)到接口代碼示例
接口傳輸協(xié)議:HTTP
接口請(qǐng)求方式:POST
數(shù)據(jù)編碼格式:UTF-8
數(shù)據(jù)傳輸格式: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方式傳輸文件
* 發(fā)送文件方法
* @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());
// 請(qǐng)求參數(shù)配置
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);
/**
* 假設(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);
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(), java.nio.charset.Charset.forName("UTF-8"));
}else {
res = "響應(yīng)失敗";
log.error("響應(yīng)失??!");
}
return res;
} catch (Exception e) {
e.printStackTrace();
log.error("調(diào)用HttpPost失敗!" + e.toString());
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.error("關(guān)閉HttpPost連接失敗!");
}
}
}
log.info("數(shù)據(jù)傳輸成功!!!!!!!!!!!!!!!!!!!!");
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){
//此處為舉例,需要添加哪些頭部信息自行添加即可
//設(shè)置時(shí)間戳,nginx,underscores_in_headers on;放到http配置里,否則nginx會(huì)忽略包含"_"的頭信息
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>總結(jié)
到此這篇關(guān)于java發(fā)送post請(qǐng)求使用multipart/form-data格式文件數(shù)據(jù)到接口的文章就介紹到這了,更多相關(guān)java發(fā)送post請(qǐng)求文件數(shù)據(jù)到接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java守護(hù)線程實(shí)例詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
在Java中有兩類線程:User Thread(用戶線程)、Daemon Thread(守護(hù)線程) 。下面通過本文給大家分享java守護(hù)線程實(shí)例詳解,需要的朋友參考下吧2017-06-06
Spring Boot實(shí)現(xiàn)簡(jiǎn)單的增刪改查
這篇文章主要介紹了Spring Boot如何實(shí)現(xiàn)簡(jiǎn)單的增刪改查,幫助大家更好的理解和學(xué)習(xí)spring boot框架,感興趣的朋友可以了解下2020-09-09
Netty源碼分析NioEventLoop線程的啟動(dòng)
這篇文章主要為大家介紹了Netty源碼分析NioEventLoop線程的啟動(dòng)示例,有需要的朋友,可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03
SpringBoot+Vue實(shí)現(xiàn)動(dòng)態(tài)菜單的思路梳理
這篇文章主要為大家詳細(xì)介紹了利用SpringBoot+Vue實(shí)現(xiàn)動(dòng)態(tài)菜單的思路梳理,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以動(dòng)手嘗試一下2022-07-07
JAVA根據(jù)ip地址獲取歸屬地的實(shí)現(xiàn)方法
本文主要介紹了JAVA根據(jù)ip地址獲取歸屬地的實(shí)現(xiàn)方法,要通過Java程序獲取IP地址對(duì)應(yīng)的城市,需要借助第三方的IP地址庫,下面就來介紹一下,感興趣的可以了解一下2023-10-10

