java 調用第三方接口,上傳附件簡單例子


 

  假設調用的第三方接口為上傳.jpg,.jpeg附件,以文件流形式上傳,無其它參數。

  比如第三方接口為c#開發,接口參數為:

        /// <summary>
        /// 上傳附件
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        [RequestSizeLimit(10_000_000)]
        [AllowAnonymous]
        public async Task<WebApiResult> UploadFile([FromForm] IFormCollection formCollection)
        {
      ...

  實現邏輯:

  a.先構建請求URL
  b. 按第三方接口文檔處理多文件上傳請求參數,構建HttpHeaders,HttpEntity
  c.使用RestTemplate請求第三方接口
  d.處理返回結果

 @PostMapping("/UploadFile")
    public String UploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        try {
            String url="http://***/UploadFile";
            if( !multipartFile.getResource().exists())
                return "文件不存在";
            String[] extObjs={".jpg",".jpeg"};
            String fileName = multipartFile.getOriginalFilename();
            String ext = FileUtil.getFileExt(fileName);
            if (!Arrays.asList(extObjs).contains(ext))
                return  "文件為空或文件格式不正確!";
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", multipartFile.getResource());

            RestTemplate request = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, headers);
            ResponseEntity<Map> response = request.postForEntity(url, requestEntity, Map.class);
            if (response.getStatusCode() != HttpStatus.OK) {
                return "返回狀態碼:"+ response.getStatusCode();
            }
            Map result  = response.getBody();
            return JSON.toJSONString(result);
        } catch (Exception ex) {
            return ex.getMessage() ;
        }
    }

  運行項目,使用postman測試:

  參考:https://blog.csdn.net/smile_68/article/details/110188355


免責聲明!

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



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