日常踩坑之使用Feign访问第三方上传文件接口

之前一直以为当想要以Feign的方式访问第三方接口上文件时,只要传一个文件的参数即可,试过之后才知道这样想也太天真了

Pom文件中添加上传表单的依赖

<dependency>
      <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form</artifactId>
        <version>3.3.0</version>
    </dependency>

    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form-spring</artifactId>
        <version>3.3.0</version>
    </dependency>

这两个依赖是必须要加的,否则会一直报错

写一个Feign的配置类

这个配置类保证了文件传输和实体传输都可以完成

@Configuration
public class FeignConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;
    @Bean
    public Encoder feignEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}

如果需要打开日志
在配置类中再注入一个Bean

@Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
    }

编写FeignClient客户端

以下以企业微信上传临时文件的接口为例

@Primary
@FeignClient(name = "vxClient",
        url = "https://qyapi.weixin.qq.com/cgi-bin")
public interface VxFeignClient {

    @PostMapping(value = "/media/upload",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE
    )
    WorkVxUploadResponse uploadFile(@RequestParam("type") String type, @RequestPart("media") MultipartFile file);

    @GetMapping(value = "media/get")
    String getFile(@RequestParam("media_id") String mediaId);
}

注意这里的produces和consumes是非常重要的配置项,表明了提交的是表单

在Service层应用

@Autowired
private VxFeignClient vxFeignClient;

public ResultVo<String> uploadFile(String title) {

   //注意这里的"media"一定要和VxFeignClient中uploadFile的@RequestPart("media")一致
   MultipartFile multipartFile = new MockMultipartFile("media", "text.xlsx", MediaType.MULTIPART_FORM_DATA_VALUE, new FileInputStream("D:\\test.xlsx"));
   uploadRes = vxFeignClient.uploadFile("file", multipartFile);
        return result;
    }

跳坑完毕,祝各位顺利

正文到此结束
评论插件初始化中...
Loading...