Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use RestTemplate to call remote interface to upload files

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about how to use RestTemplate to call the remote interface to upload files. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Description of the problem of RestTemplate calling remote interface to upload files

The third party writes an API for uploading files. The request method of this API is Post request. All the request parameters are submitted in the form of form-data form, including three parameters.

First: cookie (string type)

Second: seqNo (string type)

Third: file (file type)

Solution method

Feign components using traditional Spring Cloud sometimes have abnormal errors when calling remote interfaces to upload files. You can consider using the following two ways to upload files.

The first way

Use RestTemplate for calling

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 } / * * override parent method * if this method is not overridden and the file has a certain size, the server will have an exception * {@ code The multi-part request contained parameter data (excluding uploaded files) that exceeded} * / @ Override public String getFilename () {return fileName } / * * override the parent class contentLength method * because the {@ link org.springframework.core.io.AbstractResource#contentLength ()} method reads the file again, and when uploading the file, restTemplate uses this method to get the size. Then when you really need to read the content and find that you have finished reading it, you will report the following error. * / @ 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); / / request header is set to MediaType.MULTIPART_FORM_DATA type HttpHeaders requestHeaders = new HttpHeaders (); requestHeaders.setContentType (MediaType.MULTIPART_FORM_DATA); / / build request body MultiValueMap requestBody = new LinkedMultiValueMap (); CommonInputStreamResource commonInputStreamResource = null; try {commonInputStreamResource = new CommonInputStreamResource (fileInputStream,file.length (), file.getName ()) } catch (Exception e) {log.error ("File input stream conversion error", e);} requestBody.add ("cookie", cookie); requestBody.add ("seqNoFile", applySeqNo); requestBody.add ("file", commonInputStreamResource); HttpEntity requestEntity = new HttpEntity (requestBody, requestHeaders) / / directly call the remote interface ResponseEntity responseEntity = restTemplate.postForEntity ("http://xxx.xxx.xxx.xxx:8080/test/upload",requestEntity, String.class); System.out.println (" return result: "+ responseEntity.getBody ())} catch (Exception e) {log.error (" remote call exception: ", e);} the second way

Spring Cloud Feign component + MultiValueMap + CommonInputStreamResource

The construction of the CommonInputStreamResource object has been implemented above, so we won't repeat the construction here, just follow the one above.

Feign interface

@ Component@FeignClient (name = "taxRecodes", url = "${spider.url}", qualifier = "TaxRecodeFeignClient", fallback = TaxRecodeFallBack.class) public interface TaxRecodeFeignClient {/ * document application-upload attached to the contract information table * / @ PostMapping (value = "/ attachFile/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String attachFileUpload (MultiValueMap multiValueMap);}

Request part

@ 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 ("File input stream conversion error:", e) } MultiValueMap dto=new LinkedMultiValueMap (); 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 ("exception:", e) }} RestTemplate calls remote interface to add request header

In projects, we often encounter interfacing with third-party systems and integrate services by calling interfaces in third-party systems, adding some verification for the security of the interfaces, such as:

Basic, authority, etc., it is easier to access through the mechanism of adding authrization in the request header. Get the authorization from the third-party system, and then put the authorization on the request header when you request the API. It is easier to understand how much is not as good as directly adding the code.

/ / get the third party's authorizationString auth= OAuthContentHelper.getAuthorizationHeader (); HttpHeaders requestHeader=new HttpHeaders (); / / add the acquired authorization to the request header requestHeader.add (AuthConstants.AUTHORIZATION_HEADER,auth); / / build the request entity HttpEntity requestEntity=new HttpEntity (requestParam,requestHeaders); / / use restTemplate to call the third-party interface restTemplate.exchage (url,HttpMethod.POST,requestEntity,responseClass). After reading the above, do you have any further understanding of how to use RestTemplate to call the remote interface to upload files? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report