java如何通过url地址的到文件对象呢?(史上最全代码)
下文笔者讲述java代码通过http或https协议的方式获取文件对象的方法分享,如下所示
实现思路: 1.读取文件对象 2.借助Stream对象将文件对象转换为byte例:
/** * 远程读取文件 * * @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; } 全部引用的包,工具类可能有其他引用,取自己所需的路径就好 import com.java265.core.util.other.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.*; getNetUrlHttp方法 这里创建的是本地临时文件,所以用完了之后,不用刻意调用file.delete方法进行删除 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() { return null; } } 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; } /** * 把带路径的文件地址解析为真实文件名 /test/test888.jpg 解析为 test888.jpg * * @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; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。