• 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

  • 相关阅读:
    IOS:APP网络状态的检测
    IOS:个人笔记|UI__使用Plist文件来进行数据的读取
    IntelliJ IDEA中项目import与open的区别
    打开电脑分屏
    微服务
    自增主键和UUID
    雪花算法
    使用navicat连接阿里云上mysql
    【vue】报错This dependency was not found
    跨域问题
  • 原文地址:https://www.cnblogs.com/personblog/p/14905654.html
Copyright © 2020-2023  润新知