RestTemplate發(fā)送form-data請求上傳rul資源文件及對象參數(shù)方式
更新時間:2024年01月02日 09:59:34 作者:代號:猿a
這篇文章主要介紹了RestTemplate發(fā)送form-data請求上傳rul資源文件及對象參數(shù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
RestTemplate發(fā)送form-data請求上傳rul資源文件及對象參數(shù)
需求
上傳文件服務(wù)中的文件到其他平臺
- 接口描述:用于上傳工程日志相關(guān)資料
- 請求url:/cq-szh-projectdocumentscomputesvc/api/service/addEngineerLog
- 請求方式:POST
- 請求類型:form/data
- 請求參數(shù):包含對象參數(shù) 和 多個文件參數(shù)
其中recordPerson和uploadPerson為對象參數(shù)
files為List< MultipartFile >類型,fileInfos為JSONArray參數(shù)
/**
* 通過url獲取文件資源
* @param url
* @param fileName
* @return
* @throws IOException
*/
private static ByteArrayResource getResourceByUrl(String url,String fileName) throws IOException {
// 通過url獲取輸入流
InputStream inputStream = getFileInputStream(url);
// 讀取輸入流到字節(jié)數(shù)組
byte[] bytes = readBytes(inputStream);
// 將自己數(shù)組轉(zhuǎn)為文件資源
return new ByteArrayResource(bytes) {
@Override
public String getFilename() {
// 指定文件名稱
return fileName;
}
};
}
/*讀取網(wǎng)絡(luò)文件*/
public static InputStream getFileInputStream(String path) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//設(shè)置超時間為3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403錯誤
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到輸入流
return conn.getInputStream();
} catch (Exception e) {
logger.error("讀取網(wǎng)絡(luò)文件異常:"+path);
}
return null;
}
/**
* 讀取輸入流到字節(jié)數(shù)組
* @param in
* @return
* @throws IOException
*/
public static byte[] readBytes(InputStream in) throws IOException {
//讀取字節(jié)的緩沖
byte[] buffer = new byte[1024];
//最終的數(shù)據(jù)
byte[] result = new byte[0];
int size = 0;
while ((size = in.read(buffer)) != -1) {
int oldLen = result.length;
byte[] tmp = new byte[oldLen + size];
if (oldLen > 0) {//copy 舊字節(jié)
System.arraycopy(result, 0, tmp, 0, oldLen);
}
//copy 新字節(jié)
System.arraycopy(buffer, 0, tmp, oldLen, size);
result = tmp;
}
return result;
}
/**
* form-data的post 請求
* @param params 請求參數(shù)
* @param modelUrl 模塊url
* @return
*/
public static JSONObject postFormData( MultiValueMap<String, Object> params, String modelUrl) {
HttpHeaders headers = new HttpHeaders();
headers.add("token", token);
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
//String urlParams = url + "?params={json}";
ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlHeader+modelUrl, httpEntity, String.class);
//ResponseEntity<String> responseEntity = restTemplate.exchange(urlHeader+modelUrl, HttpMethod.POST, httpEntity, String.class);
return JSON.parseObject(responseEntity.getBody());
}
// 測試市工程項目數(shù)字化管理平臺接口
MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
params.add("accessCode",accessCode);
params.add("secretKey",secretKey);
params.add("type","GC0019001");
params.add("name","日志名稱1");
params.add("weather","天氣");
params.add("dairyDate",new Date());
params.add("recordPerson",OperationInfo.builder().operator("張三").longitude("106.57").latitude("29.55").build());
params.add("content","內(nèi)容");
params.add("uploadPerson",OperationInfo.builder().operator("張三").longitude("106.57").latitude("29.55").build());
//FileSystemResource fileSystemResource = new FileSystemResource("D:/瀏覽器下載/圖/test1.jpg");
//FileSystemResource fileSystemResource = new FileSystemResource("http://192.168.5.91:9300/statics/project_61/safety/2021/12/22/cfc8b2e9-4536-44cb-a098-25cc6ed84e6b.jpg");
//通過url獲取文件資源
ByteArrayResource contentsAsResource = getResourceByUrl("http://192.168.5.91:9300/statics/project_61/safety/2021/12/22/cfc8b2e9-4536-44cb-a098-25cc6ed84e6b.jpg","ces.jpg");
params.add("files", contentsAsResource);
List<FileInfo> fileInfos = new ArrayList<>();
// 同上面指定的文件名
fileInfos.add(FileInfo.builder().fileName("ces.jpg").documentType("GC0013001")
.unitProjectId("dc77d2c538cb4491a4b6aea006f9e48f").documentDirectoryId("3015").build());
params.add("fileInfos", JSONArray.parseArray(JSONObject.toJSONString(fileInfos)));
JSONObject jsonObject = postFormData(params, "/cq-szh-projectdocumentscomputesvc/api/service/addEngineerLog");
System.out.println(jsonObject);
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis無縫轉(zhuǎn)MyBatis-plus的基本使用
本文介紹了使用MyBatis-plus來優(yōu)化MyBatis的使用,包括引入依賴、改造Mapper、實體類注解使用、Service層方法改造等,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-10-10
spring cloud學(xué)習(xí)入門之config配置教程
這篇文章主要給大家介紹了關(guān)于spring cloud學(xué)習(xí)入門之config配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用spring cloud具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Java Map如何根據(jù)key取value以及不指定key取出所有的value
這篇文章主要介紹了Java Map如何根據(jù)key取value以及不指定key取出所有的value,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

