1、業(yè)務(wù)需求
外部服務(wù)器請(qǐng)求系統(tǒng)文件接口,系統(tǒng)接口返回文件流,并下載到本地。
2、代碼實(shí)現(xiàn)
外部接口返回map
@GetMapping("/downloadFile")
@ResponseBody
public Map<String,byte[]> downloadFile(String fileUrl){
Map<String,byte[]> map = new HashMap<>();
byte[] bytes = dowLoadFile(fileUrl);
map.put("data",bytes);
return map;
}
public byte[] dowLoadFile(String fileUrl) throws IOException{
FileInputStream in = new FileInputStream(new File(fileUrl));
ByteArrayOutputStream ous = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while(-1 != (len = in.read(buffer))){
ous.write(buffer,0,len)
}
return ous.toByteArray();
}
使用HttpUtil調(diào)用外部接口,實(shí)現(xiàn)文件下載到本地
public void downloadFile(String fileUrl) throws IOException{
String host = "http://127.0.0.1:8080";
String url = "/downloadFile?fileUrl=" + fileUrl;
String data = HttpUtil.createGet(host + url).execute().body();
JSONObject json = JSONUtil.parseObj(data);
Object obj = json.get("data");
byte[] bytes = Convert.toPrimitveByteArray(obj);
String suffix = fileUrl.substring(fileUrl.lastIndexOf("."));
String fileName = "新的文件名" + suffix;
FileOutputStream out = new FileOutputStream("D:/yyk/tt/" + fileName);
out.write(bytes);
out.close();
}
3、成果展示文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-780281.html
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-780281.html
到了這里,關(guān)于使用hutool工具類HttpUtil請(qǐng)求外部接口傳輸文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!