zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    zookeeper使用场景
    zookeeper安装配置
    hadoop 远程调试
    deep learning笔记
    Sentiment Analysis(1)-Dependency Tree-based Sentiment Classification using CRFs with Hidden Variables
    PRML阅读笔记 introduction
    Python 学习笔记(2)
    python nltk 学习笔记(5) Learning to Classify Text
    python nltk 学习笔记(4) Writing Structured Programs
    python nltk 学习笔记(3) processing raw text
  • 原文地址:https://www.cnblogs.com/personblog/p/14905654.html
Copyright © 2011-2022 走看看