/*读取网络文件*/
public static InputStream getFileInputStream(String path) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
return conn.getInputStream();
} catch (Exception e) {
logger.error("读取网络文件异常:"+path);
}
return null;
}
本文介绍了一种使用Java从网络读取文件的方法,通过HttpURLConnection获取远程文件的输入流,并设置了超时时间和请求头,以避免被服务器拒绝。此方法适用于需要从网络下载资源的应用场景。
333

被折叠的 条评论
为什么被折叠?



