筆記:將一個文件服務器上的文件(一個返回文件數據的url)作為另一個http接口的請求參數
最近有這么個需求,需要往某一個業務的外部接口上傳文件信息,但是現在沒有現成的文件,只在數據庫存了對應的url,比如一張圖片:
CSDN個人信息默認圖片
https://profile-avatar.csdnimg.cn/default.jpg!3
現在我有這么一個地址,返回的是二進制流數據,通常http傳文件數據的話,需要通過一個具體的文件,即需要先下載文件。
在此感謝百度告訴我還有臨時文件的創建方式,我也不知道百度ai從哪里參考的代碼,在此同步感謝。
在這里使用http請求用的hutool的工具類:
<!-- hutool 的依賴配置-->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-bom</artifactId><version>5.8.18</version>
</dependency>
下面,附上具體的實現代碼邏輯:
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import java.io.File;
import java.io.IOException;public class UploadFile {public static void main(String[] args) throws IOException {//獲取url對應的文件二進制流數據//源文件地址(可以在網頁上任意找一個圖片地址,我這里用的CSDN個人信息默認圖片)String fileUrl = "https://profile-avatar.csdnimg.cn/default.jpg!3";String fileName = "CSDN個人信息默認圖片.jpg";//獲取文件數據HttpResponse response = HttpUtil.createGet(fileUrl).execute();if(response.isOk()) {byte[] bytes = response.bodyBytes();//如果返回有數據,則上傳if(bytes != null && bytes.length > 0){//創建臨時文件int index = fileName.lastIndexOf(".");String prefix = fileName.substring(0, index);//CSDN個人信息默認圖片String suffix = fileName.substring(index);//.jpg//生成空臨時文件File tempFile = File.createTempFile(prefix, suffix);tempFile.deleteOnExit();//程序結束時自動刪除文件//寫入數據FileUtil.writeBytes(bytes, tempFile);//需要文件參數的http接口String url = "http://xxxxx/xxxxx";String result = HttpUtil.createPost(url).contentType("multipart/form-data").form("name", fileName).form("file", tempFile).execute().body();// 打印響應內容System.out.println(response.body());}}}
}
重點其實就三步:
1、通過接口獲取到文件url對應的二進制數據。
2、通過生成臨時文件,將返回的二進制數據寫入臨時文件。
3、將臨時文件作為參數發送http請求。