1. Spring 中调用文件接口
- 导入jar
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.9</version>
<scope>test</scope>
</dependency>
- 通过MultipartEntityBuilder构造请求的内容参数
public void sendFile(){
String url = "http://localhost:8588/email/sendWithAttachments";
File file = new File("C:\\Users\\PC\\Desktop\\spring.md");
HttpPost httpPost = new HttpPost(url);
//FileBody bin = new FileBody(file);
//StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
// 传递文件有三种方式 1. 发送File 2.发送InputStream 3.发送Byte[]
FileBody fileBody = new FileBody(file);
InputStreamBody file2Body = new InputStreamBody(new FileInputStream(file),file.getName());
ByteArrayBody fileByte = new ByteArrayBody(File2byte(file),file.getName());
// 构造请求体
HttpEntity reqEntity = MultipartEntityBuilder.create()
//.setCharset(CharsetUtil.UTF_8) //万恶之源,测试很多次才发现原来是这玩意影响的
.setMode(HttpMultipartMode.RFC6532)//加上此行代码解决返回中文乱码问题
// .setContentType(ContentType.MULTIPART_FORM_DATA)
// .addPart("files", fileBody)
.addPart("fileList", fileByte)
//邮件主题
.addPart("subject", new StringBody("hello color",ContentType.APPLICATION_JSON))
// 邮件内容
.addPart("content", new StringBody("color",ContentType.APPLICATION_JSON))
.addPart("receiveList", new StringBody("[email protected]",ContentType.APPLICATION_JSON))
.build();
httpPost.setEntity(reqEntity);
// 请求接口
CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
}
2. Feign调用第三方文件接口
Feign传表单数据参考了 https://blog.csdn.net/ytzzh0726/article/details/79731343 这一片文章,是通过传递Map参数来实现Feign传表单数据,本文章在此基础上,新加了传递自定义实体类来实现Feign传表单数据
1. Feign 表单提交文件jar包依赖
<!-- 对应SpringCloud版本Finchley.RELEASE-->
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.2.2</version>
</dependency>
2. FeignClient 接口声明
@FeignClient(name = "TestApi", url = "http://localhost:8588", configuration = TestApi.FeignMultipartSupportConfig.class)
public interface TestApi {
@PostMapping(path = "/email/sendWithAttachments", produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Object sendByMap(Map<String,Object> param);
@PostMapping(path = "/email/sendWithAttachments", produces = {
MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Object sndTestBody(MailPojo pojo);
//自定义文件上传编码器
class