之前一直以為當想要以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;
}
跳坑完畢,祝各位順利