文字标题:java通过url得到文件对象(支持http和https)
作者:锅巴
1.场景:通过一个url地址来得到一个文件,此方式就是通过一个url将文件下载到本地的临时文件,直接上代码
/**
* 远程读取文件
*
* @param netUrl
* @return
*/
public static File getNetUrl(String netUrl) {
//判断http和https
File file = null;
if (netUrl.startsWith("https://")) {
file = getNetUrlHttps(netUrl);
} else {
file = getNetUrlHttp(netUrl);
}
return file;
}
全部引用的包,工具类可能有其他引用,取自己所需的路径就好
2.getNetUrlHttp方法
这里创建的是本地临时文件,所以用完了之后,不用刻意调用file.delete方法进行删除
import com.guoba.util.X509TrustUtiil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.*;
public static File getNetUrlHttp(String netUrl) {
//对本地文件命名
String fileName = StringUtils.reloadFile(netUrl);
File file = null;
URL urlfile;
InputStream inStream = null;
OutputStream os = null;
try {
file = File.createTempFile("net_url", fileName);
//下载
urlfile = new URL(netUrl);
inStream = urlfile.openStream();
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
log.error("远程图片获取错误:"+netUrl);
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
if (null != inStream) {
inStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
getNetUrlHttps
这个方法就相对于要麻烦很多了,毕竟涉及到ssl,很多人再请求的时候绕不开ssl,这里可以通过代码进行处理
SSLContext不需要其他包,使用java自带的,无需import
/**
* 下载文件到本地(支持https)
*
* @param fileUrl 远程地址
* @throws Exception
*/
public static File getNetUrlHttps(String fileUrl) {
//对本地文件进行命名
String file_name = StringUtils.reloadFile(fileUrl);
File file = null;
DataInputStream in = null;
DataOutputStream out = null;
try {
file = File.createTempFile("net_url", file_name);
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
sslcontext.init(null, new TrustManager[]{new X509TrustUtiil()}, new java.security.SecureRandom());
URL url = new URL(fileUrl);
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslsession) {
logger.warn("WARNING: Hostname is not matched for cert.");
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
// 读文件流
in = new DataInputStream(urlCon.getInputStream());
out = new DataOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[2048];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
} catch (Exception e) {
log.error("远程图片获取错误:"+fileUrl);
e.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return file;
}
工具类X509TrustUtiil
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class X509TrustUtiil implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
ps:最后放两个StringUtils工具类
/**
* 重命名,UUIU
*
* @param oleFileName
* @return
*/
public static String reloadFile(String oleFileName) {
oleFileName = getFileName(oleFileName);
if (StringUtils.isEmpty(oleFileName)) {
return oleFileName;
}
//得到后缀
if (oleFileName.indexOf(".") == -1) {
//对于没有后缀的文件,直接返回重命名
return UniqId.getUid();
}
String[] arr = oleFileName.split("\\.");
// 根据uuid重命名图片
String fileName = UniqId.getUid() + "." + arr[arr.length - 1];
return fileName;
}
/**
* 把带路径的文件地址解析为真实文件名 /25h/upload/hc/1448089199416_06cc07bf-7606-4a81-9844-87d847f8740f.mp4 解析为 1448089199416_06cc07bf-7606-4a81-9844-87d847f8740f.mp4
*
* @param url
*/
public static String getFileName(final String url) {
if (StringUtils.isEmpty(url)) {
return url;
}
String newUrl = url;
newUrl = newUrl.split("[?]")[0];
String[] bb = newUrl.split("/");
String fileName = bb[bb.length - 1];
return fileName;
}