公司项目遇到,对接第三方接口时需要根据链接获取网络文件保存到我们自己的服务器,但是本服务无法访问外网,只能通过请求另一个服务去访问外网。故准备由外网服务获取网络文件并将文件流推送回内网服务进行保存。
外网服务接口:
@RestController
@RequestMapping("/url")
@ApiType(name = "内部接口转发")
public class UrlController extends GenericDataForFileController<HttpRequest, GeneralResponseDto> {
@Autowired
private HttpServletResponse response;
@Override
public void execute(HttpRequest req, GeneralResponseDto respData) {
try {
URL url = new URL(req.getUrl());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(10 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + req.getParam().toString());
InputStream is = conn.getInputStream();
try {
byte[] b = new byte[1024];
int length;
while ((length = is.read(b)) > 0) {
response.getOutputStream().write(b, 0, length);
}
} catch (IOException e) {
throw e;
} finally {
if (response.getOutputStream() != null) {
try {
response.getOutputStream().close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (MalformedURLException e) {
logger.info("文件下载失败");
} catch (IOException e) {
logger.info("文件下载失败");
}
}
}
内网服务接口,本处文件保存用了hutool的FileUtil,属于本地保存:
/**
* 从网络Url中下载文件
*
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
private void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
URL url = new URL(getStream);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置body内的参数,put到JSONObject中
JSONObject param = new JSONObject();
param.put("url", urlStr);
param.put("param", fileName.substring(fileName.lastIndexOf("/") + 1));
conn.setRequestProperty("Content-Type", "application/json");
//设置超时间为3秒
conn.setConnectTimeout(10 * 1000);
//请求post方式
conn.setRequestMethod("POST");
// Post请求不能使用缓存
conn.setUseCaches(false);
// 设置是否从HttpURLConnection输入,默认值为 true
conn.setDoInput(true);
// 设置是否使用HttpURLConnection进行输出,默认值为 false
conn.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
writer.write(param.toString());
writer.close();
//得到输入流
InputStream inputStream = conn.getInputStream();
if (inputStream.available() < 1000) {
throw new IOException("文件获取失败");
}
String upload = savePath + "/" + fileName;
//写入
FileUtil.writeFromStream(inputStream, upload);
}