笔记:将一个文件服务器上的文件(一个返回文件数据的url)作为另一个http接口的请求参数
最近有这么个需求,需要往某一个业务的外部接口上传文件信息,但是现在没有现成的文件,只在数据库存了对应的url,比如一张图片:
CSDN个人信息默认图片
https://profile-avatar.csdnimg.cn/default.jpg!3
现在我有这么一个地址,返回的是二进制流数据,通常http传文件数据的话,需要通过一个具体的文件,即需要先下载文件。
在此感谢百度告诉我还有临时文件的创建方式,我也不知道百度ai从哪里参考的代码,在此同步感谢。
在这里使用http请求用的hutool的工具类:
<!-- hutool 的依赖配置-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-bom</artifactId>
<version>5.8.18</version>
</dependency>
下面,附上具体的实现代码逻辑:
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import java.io.File;
import java.io.IOException;
public class UploadFile {
public static void main(String[] args) throws IOException {
//获取url对应的文件二进制流数据
//源文件地址(可以在网页上任意找一个图片地址,我这里用的CSDN个人信息默认图片)
String fileUrl = "https://profile-avatar.csdnimg.cn/default.jpg!3";
String fileName = "CSDN个人信息默认图片.jpg";
//获取文件数据
HttpResponse response = HttpUtil.createGet(fileUrl).execute();
if(response.isOk()) {
byte[] bytes = response.bodyBytes();
//如果返回有数据,则上传
if(bytes != null && bytes.length > 0){
//创建临时文件
int index = fileName.lastIndexOf(".");
String prefix = fileName.substring(0, index);//CSDN个人信息默认图片
String suffix = fileName.substring(index);//.jpg
//生成空临时文件
File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();//程序结束时自动删除文件
//写入数据
FileUtil.writeBytes(bytes, tempFile);
//需要文件参数的http接口
String url = "http://xxxxx/xxxxx";
String result = HttpUtil.createPost(url).contentType("multipart/form-data")
.form("name", fileName).form("file", tempFile).execute().body();
// 打印响应内容
System.out.println(response.body());
}
}
}
}
重点其实就三步:
1、通过接口获取到文件url对应的二进制数据。
2、通过生成临时文件,将返回的二进制数据写入临时文件。
3、将临时文件作为参数发送http请求。