根据URL下载图片到本地

博客围绕Java图片下载展开,涉及图片下载过程中的安全验证相关内容,聚焦信息技术领域中Java编程在图片处理方面的应用及安全保障。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
     * 根据URL下载图片
     * @throws IOException 
     */
    public static String savePicData(String urlLink,String dir,String pkid) throws Exception
    {
        System.out.println(urlLink);
         String[] typeList = urlLink.split("\\.");
         String type = typeList[typeList.length-1];//添加后缀
         URL url = new URL(urlLink);
        

         //某些图片访问或者下载需要安全验证
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         if (conn instanceof HttpsURLConnection)  {
             SSLContext sc = SSLContext.getInstance("SSL");
             sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
             ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());
             ((HttpsURLConnection) conn).setHostnameVerifier(new TrustAnyHostnameVerifier());
         }
         conn.connect();
         System.out.println(conn.getResponseCode());

         // 得到输入流  
         java.io.InputStream inputStream = conn.getInputStream();

         ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
                  byte[] buff = new byte[100];  
                  int rc = 0;  
                  while ((rc = inputStream.read(buff, 0, 100)) > 0) {  
                      swapStream.write(buff, 0, rc);  
                  }  
         // 获取自己数组  
         byte[] getData =swapStream.toByteArray();

         // 文件保存位置  
         File saveDir = new File(dir);  

         if (!saveDir.exists()) {  
             saveDir.mkdirs();  
         }  
         String path = saveDir + File.separator + pkid + "." + type;
         File file = new File(path);  
         FileOutputStream fos = new FileOutputStream(file);
         fos.write(getData);
         if (fos != null) {  
             fos.close();  
         }  

         if (inputStream != null) {  
             inputStream.close();  
         }  
         
       return  path;
    }



private static class TrustAnyTrustManager implements X509TrustManager {
        
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }
    
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

 

### Java 实现从 URL 下载视频到本地文件的示例 以下是通过 Java 编程语言实现从指定 URL 下载视频并保存至本地的一个完整方法。此过程涉及网络请求以及字节流操作。 ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class VideoDownloader { public static void downloadVideo(String videoUrl, String destinationFile) throws IOException { URL url = new URL(videoUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); // Check if the connection is successful if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(destinationFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); // Write bytes read into output stream. } outputStream.close(); // Close streams after writing all content. inputStream.close(); } else { throw new IOException("No file to download. Server replied HTTP code: " + responseCode); } httpConn.disconnect(); } public static void main(String[] args) { try { String videoUrl = "https://example.com/sample-video.mp4"; // Replace with actual video URL. String destinationFilePath = "/path/to/save/video.mp4"; // Specify desired path. downloadVideo(videoUrl, destinationFilePath); System.out.println("Download completed successfully."); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码展示了如何利用 `InputStream` 和 `OutputStream` 将远程资源写入本地磁盘[^1]。具体而言: - 使用 `HttpURLConnection` 建立连接,并验证服务器返回的状态码是否正常。 - 如果状态码为 `HTTP_OK`(即 200),则读取输入流中的数据并通过缓冲区逐步将其写入目标文件中。 需要注意的是,在实际应用过程中可能还需要考虑异常处理机制、超时设置等问题以增强程序健壮性。 #### 关于内存使用的注意事项 当执行此类大文件传输任务时,应当密切关注应用程序所消耗的 RAM 数量及其随负载变化的趋势[^2]。如果发现随着输入规模增大而显著增加,则需优化算法设计或者调整 JVM 参数来控制最大堆大小等配置项。 #### 卷积神经网络的相关说明 尽管本主题聚焦于媒体文件的操作而非图像识别领域,但值得一提的是卷积神经网络(CNNs),它们擅长提取空间特征用于图片分类等工作流程之中[^3]。不过这与当前讨论的主题无直接关联。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值