文字标题:java通过url得到文件对象(支持http和https)
作者:锅巴
1.场景:通过一个url地址来得到一个文件,此方式就是通过一个url将文件下载到本地的临时文件,直接上代码
| |
| |
| |
| |
| |
| |
| public static File getNetUrl(String netUrl) { |
| |
| 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 |
| |
| |
| |
| |
| |
| |
| 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 { |
| |
| |
| } |
| |
| @Override |
| public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { |
| |
| |
| } |
| |
| @Override |
| public X509Certificate[] getAcceptedIssuers() { |
| |
| return null; |
| } |
| |
| } |
| |
ps:最后放两个StringUtils工具类
| |
| |
| |
| |
| |
| |
| 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("\\."); |
| |
| String fileName = UniqId.getUid() + "." + arr[arr.length - 1]; |
| |
| return fileName; |
| } |
| |
| |
| |
| |
| |
| |
| 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; |
| } |
| |
用好以上类【工具类】,就可以通过一个url将远程地址的文件转化为本地文件了(_)