使用RestTemplate 調(diào)用遠(yuǎn)程接口上傳文件方式
RestTemplate 調(diào)用遠(yuǎn)程接口上傳文件
問(wèn)題描述
第三方寫(xiě)了一個(gè)文件上傳的接口,該接口的請(qǐng)求方式為Post請(qǐng)求,請(qǐng)求參數(shù)全部是以form-data表單形式進(jìn)行提交,包含三個(gè)參數(shù)
- 第一個(gè):cookie(字符串類型)
- 第二個(gè):seqNo(字符串類型)
- 第三個(gè):file(文件類型)
解決方法
使用傳統(tǒng)的Spring Cloud的Feign組件在調(diào)用遠(yuǎn)程接口實(shí)現(xiàn)文件上傳時(shí)有時(shí)會(huì)出現(xiàn)異常錯(cuò)誤,可考慮使用下述兩種方式文件上傳
第一種方式
使用RestTemplate進(jìn)行調(diào)用
import org.springframework.core.io.InputStreamResource; import java.io.InputStream; public class CommonInputStreamResource extends InputStreamResource { private long length; private String fileName; public CommonInputStreamResource(InputStream inputStream, long length, String fileName) { super(inputStream); this.length = length; this.fileName = fileName; } /** * 覆寫(xiě)父類方法 * 如果不重寫(xiě)這個(gè)方法,并且文件有一定大小,那么服務(wù)端會(huì)出現(xiàn)異常 * {@code The multi-part request contained parameter data (excluding uploaded files) that exceeded} */ @Override public String getFilename() { return fileName; } /** * 覆寫(xiě)父類 contentLength 方法 * 因?yàn)?{@link org.springframework.core.io.AbstractResource#contentLength()}方法會(huì)重新讀取一遍文件, * 而上傳文件時(shí),restTemplate 會(huì)通過(guò)這個(gè)方法獲取大小。然后當(dāng)真正需要讀取內(nèi)容的時(shí)候,發(fā)現(xiàn)已經(jīng)讀完,會(huì)報(bào)如下錯(cuò)誤。 */ @Override public long contentLength() { long estimate = length; return estimate == 0 ? 1 : estimate; } public void setLength(long length) { this.length = length; } public void setFileName(String fileName) { this.fileName = fileName; } }
try{ String applySeqNo = "123456"; String cookie="654321"; File file=new File("E:\\1.rar"); FileInputStream fileInputStream=new FileInputStream(file); //請(qǐng)求頭設(shè)置為MediaType.MULTIPART_FORM_DATA類型 HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); //構(gòu)建請(qǐng)求體 MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); CommonInputStreamResource commonInputStreamResource = null; try { commonInputStreamResource = new CommonInputStreamResource(fileInputStream,file.length(),file.getName()); } catch (Exception e) { log.error("文件輸入流轉(zhuǎn)換錯(cuò)誤",e); } requestBody.add("cookie", cookie); requestBody.add("seqNoFile", applySeqNo); requestBody.add("file",commonInputStreamResource); HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders); //直接調(diào)用遠(yuǎn)程接口 ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://xxx.xxx.xxx.xxx:8080/test/upload",requestEntity, String.class); System.out.println("返回結(jié)果:"+responseEntity.getBody()) }catch (Exception e){ log.error("遠(yuǎn)程調(diào)用出現(xiàn)異常:", e); }
第二種方式
Spring Cloud Feign組件 + MultiValueMap + CommonInputStreamResource
CommonInputStreamResource對(duì)象的構(gòu)造在上面已經(jīng)實(shí)現(xiàn)了這里就不再重復(fù)構(gòu)造,沿用上面的那個(gè)就行
feign接口
@Component @FeignClient(name = "taxRecodes", url = "${spider.url}", qualifier = "TaxRecodeFeignClient",fallback = TaxRecodeFallBack.class) public interface TaxRecodeFeignClient { /** * 單證申請(qǐng)-合同信息表附件上傳 */ @PostMapping(value = "/attachFile/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String attachFileUpload(MultiValueMap<String, Object> multiValueMap); }
請(qǐng)求部分
@PostMapping("/upload") public void upload(){ try { File file=new File("E:\\1.rar"); FileInputStream fileInputStream=new FileInputStream(file); CommonInputStreamResource commonInputStreamResource = null; try { commonInputStreamResource = new CommonInputStreamResource(fileInputStream,fileInputStream.available(),file.getName()); } catch (Exception e) { log.error("文件輸入流轉(zhuǎn)換錯(cuò)誤:",e); } MultiValueMap<String, Object> dto=new LinkedMultiValueMap<String, Object>(); dto.add("cookie","xxx"); dto.add("file",commonInputStreamResource); dto.add("seqNoFile","xxx"); String returnInfo = taxRecodeFeignClient.attachFileUpload(dto); JSONObject returnInfoJsonObject = JSONObject.parseObject(returnInfo); }catch (Exception e){ log.error("異常:",e); } }
RestTemplate調(diào)用遠(yuǎn)程接口添加請(qǐng)求頭
項(xiàng)目中我們經(jīng)常會(huì)碰到與第三方系統(tǒng)對(duì)接,通過(guò)調(diào)用第三方系統(tǒng)中的接口來(lái)集成服務(wù),為了接口的安全性都為加一些驗(yàn)證,比如:
basic、authority等,通過(guò)請(qǐng)求頭添加authrization的機(jī)制比較容易接入,從第三方系統(tǒng)獲取到authorization,然后請(qǐng)求接口時(shí)在請(qǐng)求頭上帶上獲取到的authorization,說(shuō)了怎么多不如直接上代碼更容易理解。
// 獲取第三方的authorization String auth= OAuthContentHelper.getAuthorizationHeader(); HttpHeaders requestHeader=new HttpHeaders(); // 將獲取到的authorization添加到請(qǐng)求頭 requestHeader.add(AuthConstants.AUTHORIZATION_HEADER,auth); // 構(gòu)建請(qǐng)求實(shí)體 HttpEntity<Object> requestEntity=new HttpEntity(requestParam,requestHeaders); // 使用restTemplate調(diào)用第三方接口 restTemplate.exchage(url,HttpMethod.POST,requestEntity,responseClass);
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
EasyExcel工具讀取Excel空數(shù)據(jù)行問(wèn)題的解決辦法
EasyExcel是阿里巴巴開(kāi)源的一個(gè)excel處理框架,以使用簡(jiǎn)單,節(jié)省內(nèi)存著稱,下面這篇文章主要給大家介紹了關(guān)于EasyExcel工具讀取Excel空數(shù)據(jù)行問(wèn)題的解決辦法,需要的朋友可以參考下2022-08-08Springboot整合hutool驗(yàn)證碼的實(shí)例代碼
在 Spring Boot 中,你可以將 Hutool 生成驗(yàn)證碼的功能集成到 RESTful API 接口中,這篇文章主要介紹了Springboot整合hutool驗(yàn)證碼,需要的朋友可以參考下2024-08-08SpringBoot如何統(tǒng)一清理數(shù)據(jù)
這篇文章主要介紹了SpringBoot如何統(tǒng)一清理數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Spring Security中的Servlet過(guò)濾器體系代碼分析
這篇文章主要介紹了Spring Security中的Servlet過(guò)濾器體系,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07springboot3.x版本集成log4j沖突以及解決log4j沖突不生效問(wèn)題
由于Spring Boot自帶的Logback與Log4j沖突,去除了Logback的jar包后仍存在,原因是其他包也引入了Logback,解決方法是找到并去除引入Logback的其他包,如actuator包,并更新Maven2024-11-11Spring源碼解析之循環(huán)依賴的實(shí)現(xiàn)流程
這篇文章主要介紹了Spring源碼解析之循環(huán)依賴的實(shí)現(xiàn)流程,文章基于Java的相關(guān)內(nèi)容展開(kāi)循環(huán)依賴的實(shí)現(xiàn)流程,需要的小伙伴可以參考一下2022-07-07