RestTemplate發(fā)送form-data請(qǐng)求上傳rul資源文件及對(duì)象參數(shù)方式
更新時(shí)間:2024年01月02日 09:59:34 作者:代號(hào):猿a
這篇文章主要介紹了RestTemplate發(fā)送form-data請(qǐng)求上傳rul資源文件及對(duì)象參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
RestTemplate發(fā)送form-data請(qǐng)求上傳rul資源文件及對(duì)象參數(shù)
需求
上傳文件服務(wù)中的文件到其他平臺(tái)
- 接口描述:用于上傳工程日志相關(guān)資料
- 請(qǐng)求url:/cq-szh-projectdocumentscomputesvc/api/service/addEngineerLog
- 請(qǐng)求方式:POST
- 請(qǐng)求類(lèi)型:form/data
- 請(qǐng)求參數(shù):包含對(duì)象參數(shù) 和 多個(gè)文件參數(shù)
其中recordPerson和uploadPerson為對(duì)象參數(shù)
files為L(zhǎng)ist< MultipartFile >類(lèi)型,fileInfos為JSONArray參數(shù)
/**
* 通過(guò)url獲取文件資源
* @param url
* @param fileName
* @return
* @throws IOException
*/
private static ByteArrayResource getResourceByUrl(String url,String fileName) throws IOException {
// 通過(guò)url獲取輸入流
InputStream inputStream = getFileInputStream(url);
// 讀取輸入流到字節(jié)數(shù)組
byte[] bytes = readBytes(inputStream);
// 將自己數(shù)組轉(zhuǎn)為文件資源
return new ByteArrayResource(bytes) {
@Override
public String getFilename() {
// 指定文件名稱(chēng)
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è)置超時(shí)間為3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403錯(cuò)誤
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 請(qǐng)求
* @param params 請(qǐng)求參數(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());
}
// 測(cè)試市工程項(xiàng)目數(shù)字化管理平臺(tái)接口
MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
params.add("accessCode",accessCode);
params.add("secretKey",secretKey);
params.add("type","GC0019001");
params.add("name","日志名稱(chēng)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");
//通過(guò)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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決Tomcat啟動(dòng)報(bào)異常java.lang.ClassNotFoundException問(wèn)題
這篇文章主要介紹了解決Tomcat啟動(dòng)報(bào)異常java.lang.ClassNotFoundException問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
Springboot+Stomp協(xié)議實(shí)現(xiàn)聊天功能
本示例實(shí)現(xiàn)一個(gè)功能,前端通過(guò)websocket發(fā)送消息給后端服務(wù),后端服務(wù)接收到該消息時(shí),原樣將消息返回給前端,前端技術(shù)棧html+stomp.js,后端SpringBoot,需要的朋友可以參考下2024-02-02
Java根據(jù)實(shí)體生成SQL數(shù)據(jù)庫(kù)表的示例代碼
這篇文章主要來(lái)和大家分享一個(gè)Java實(shí)現(xiàn)根據(jù)實(shí)體生成SQL數(shù)據(jù)庫(kù)表的代碼,文中的實(shí)現(xiàn)代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-07-07

