java發(fā)送form-data請求實現(xiàn)文件上傳的示例代碼
一、業(yè)務(wù)需求:
需要請求第三方接口上傳文件,該請求類型是form-data請求
二、postmant請求結(jié)果如下

三、maven依賴:
<!--http-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
</dependency>
四、java實現(xiàn)請求
public static void test() {
String goodsUrl = "http://0.0.0.0:7000/pangu/";
//本地文件位置
String fileName = "D:\\222.png";
String str = null;
try {
//添加請求頭
HashMap<String, String> map = new HashMap<>();
//map.put("token", CommonConstant.token);
File file = new File(fileName);
str = doPostUploadFile(goodsUrl + "/sacw/CommonConfig/uploadFile", map, file);
if(file.exists()) {
//boolean delete = file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* post請求提交form-data上傳文件
*
* @param url 上傳地址
* @param headers 請求頭
* @param file 上傳文件
* @return
*/
public static String doPostUploadFile(String url, Map<String, String> headers, File file) {
HttpPost httpPost = new HttpPost(url);
packageHeader(headers, httpPost);
String fileName = file.getName();
CloseableHttpResponse response = null;
String respContent = null;
long startTime = System.currentTimeMillis();
// 設(shè)置請求頭 boundary邊界不可重復(fù),重復(fù)會導(dǎo)致提交失敗
String boundary = "-------------------------" + UUID.randomUUID().toString();
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// 創(chuàng)建MultipartEntityBuilder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 設(shè)置字符編碼
builder.setCharset(StandardCharsets.UTF_8);
// 模擬瀏覽器
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 設(shè)置邊界
builder.setBoundary(boundary);
// 設(shè)置multipart/form-data流文件
builder.addPart("sendfile", new FileBody(file));
builder.addTextBody("fileType", "1");
// application/octet-stream代表不知道是什么格式的文件
builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() < 400) {
HttpEntity he = response.getEntity();
if (he != null) {
respContent = EntityUtils.toString(he, "UTF-8");
}
} else {
logger.error("對方響應(yīng)的狀態(tài)碼不在符合的范圍內(nèi)!");
throw new RuntimeException();
}
return respContent;
} catch (Exception e) {
logger.error("網(wǎng)絡(luò)訪問異常,請求url地址={},響應(yīng)體={},error={}", url, response, e);
throw new RuntimeException();
} finally {
logger.info("統(tǒng)一外網(wǎng)請求參數(shù)打印,post請求url地址={},響應(yīng)={},耗時={}毫秒", url, respContent, (System.currentTimeMillis() - startTime));
try {
if (response != null) {
response.close();
}
if(null != httpClient){
httpClient.close();
}
} catch (IOException e) {
logger.error("請求鏈接釋放異常", e);
}
}
}
/**
* 封裝請求頭
*
* @param paramsHeads
* @param httpMethod
*/
private static void packageHeader(Map<String, String> paramsHeads, HttpRequestBase httpMethod) {
if (null!= paramsHeads && paramsHeads.size()>0) {
Set<Map.Entry<String, String>> entrySet = paramsHeads.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
} 注意:這里的builder.addPart("sendfile", new FileBody(file));,multipartFile對應(yīng)form表單的字段名稱。
參考:Java發(fā)送form-data請求實現(xiàn)文件上傳_IceFloe_Rot的博客-CSDN博客
到此這篇關(guān)于java發(fā)送form-data請求實現(xiàn)文件上傳的示例代碼的文章就介紹到這了,更多相關(guān)java發(fā)送form-data請求上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- java?11新特性HttpClient主要組件及發(fā)送請求示例詳解
- Java通過httpclient比較重定向和請求轉(zhuǎn)發(fā)
- Java HttpClient執(zhí)行請求時配置cookie流程詳細講解
- Java HttpClient-Restful工具各種請求高度封裝提煉及總結(jié)
- java中httpclient封裝post請求和get的請求實例
- java爬蟲之使用HttpClient模擬瀏覽器發(fā)送請求方法詳解
- Java請求調(diào)用參數(shù)格式為form-data類型的接口代碼示例
- Java后臺接收數(shù)據(jù)的三種方式(url、form-data與application/json)
- Java httpclient請求form-data格式并設(shè)置boundary代碼實現(xiàn)方法
相關(guān)文章
淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級原理
這篇文章主要介紹了淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級原理,Hystrix 是 Netflix 的一款開源的容錯框架,通過服務(wù)隔離來避免由于依賴延遲、異常,引起資源耗盡導(dǎo)致系統(tǒng)不可用的解決方案,需要的朋友可以參考下2023-05-05
Spring Boot 2.0.0 終于正式發(fā)布-重大修訂版本
北京時間 2018 年 3 月 1 日早上,如約發(fā)布的 Spring Boot 2.0 在同步至 Maven 倉庫時出現(xiàn)問題,導(dǎo)致在 GitHub 上發(fā)布的 v2.0.0.RELEASE 被撤回2018-03-03
idea resources目錄下的application.properties不能自動提示問題
這篇文章主要介紹了idea resources目錄下的application.properties不能自動提示問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
SpringBoot項目導(dǎo)入aliyun oss starter依賴后啟動報錯問題
這篇文章主要介紹了SpringBoot項目導(dǎo)入aliyun oss starter依賴后啟動報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
SpringBoot集成H2內(nèi)存數(shù)據(jù)庫的方法
H2是Thomas Mueller提供的一個開源的、純java實現(xiàn)的關(guān)系數(shù)據(jù)庫。本文主要介紹了SpringBoot集成H2內(nèi)存數(shù)據(jù)庫,具有一定的參考價值,感興趣的可以了解一下2021-09-09
Springboot實現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并保存到本地
這篇文章主要為大家詳細介紹了Springboot實現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并將文件保存到本地效果的方法,文中的示例代講解詳細,需要的可以參考一下2022-09-09

