使用RestTemplate調用接口上傳文件


場景

接口接受一個文件,緩存在本地,驗證文件的完整性及內容,然后將文件上傳至雲服務器;

下面只寫利用RestTemplate將文件上傳至雲服務器,至於文件上傳以及緩存在本地可以參考:JAVA文件上傳:RESTFUL接口接收上傳文件,緩存在本地

代碼

@Test
    public void restTemplateTransferFile(){
        final String filePath = "F:";
        final String fileName = "testFile.txt";
        final String url = "http://localhost:8080/file/upload";

        RestTemplate restTemplate = new RestTemplate();

        //設置請求頭
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);

        //設置請求體,注意是LinkedMultiValueMap
        FileSystemResource fileSystemResource = new FileSystemResource(filePath+"/"+fileName);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("filename",fileName);

     //用HttpEntity封裝整個請求報文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        String s = restTemplate.postForObject(url, files, String.class);
        System.out.println(s);
    }

 

 

利用HttpHeader將請求頭的設置為"multipart/form-data";

利用FileSystemResource封裝文件內容,將請求體用LinkedMultiValueMap封裝;

再用HttpEntity封裝整個請求報文;

最后利用RestTemplate post請求。

 

注意

這里我使用的是原生的RestTemplate(直接new的),比如使用OAuth2RestTemplate用上面這種方式傳輸文件,可能出現RestClientException,原因可能是OAuth2RestTemplate的HttpMessageConvert不能匹配MultiValueMap。

 

 

參考:https://blog.csdn.net/kahhy/article/details/78115698


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM