java - 如何使用 java 启用 Https 下载

标签 java httpurlconnection download-manager

我使用以下代码来下载...

public void run()
{
    RandomAccessFile file=null;    //download wiil be stored in this file
    InputStream in=null;           //InputStream to read from
    try
    {

         HttpURLConnection conn=(HttpURLConnection)url.openConnection();    
     conn.setRequestProperty("Range","bytes="+downloaded+"-");
     if(user!=null && pwd!=null){
        String userPass=user+":"+pwd;
        String encoding = new sun.misc.BASE64Encoder().encode (userPass.getBytes());
        conn.setRequestProperty ("Authorization", "Basic " + encoding); 
     }

         conn.connect();

     //..More code 

     if(status==Status.CONNECTING)
        status=Status.DOWNLOADING;


         file=new RandomAccessFile(location,"rw");
         file.seek(downloaded);
         in=conn.getInputStream();      
     byte[] buffer;     
         while(status==Status.DOWNLOADING)
         {
            if(size-downloaded>Constants.MAX_BUFFER_SIZE)  //MAX_BUFFER_SIZE=1024
      buffer=new byte[Constants.MAX_BUFFER_SIZE];
    else
      buffer=new byte[size-downloaded];

        int read=in.read(buffer);  //reading in Buffer

        if(read==-1)
           break;

       //write to file
        file.write(buffer,0,read);
        downloaded+=read;

        //..More code
        }  //end of while


}

我正在使用上面的代码循环从 URL 下载文件。我正在使用下载(阅读)中的InputStream。我应该使用 channel 来提高性能吗?

请指导我观看我的代码以提高下载速度。

最佳答案

BufferedInputStream 包装 InputStream 并增加缓冲区大小。即使在服务器端使用起来相当好,切换到 channel 实现在客户端也不会带来太大改进。

您还应该只创建一个byte[]并重复使用它。不要在循环中的每次迭代中创建它。

关于java - 如何使用 java 启用 Https 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6266973/

相关文章:

java - 计算Google App Engine/Java中的时差

Java URLConnection 适用于 windows,但不适用于 linux

android - 将Android客户端连接到python服务器时响应代码404

java - JCombobox 是否应该具有来自 MVC 架构后端的对象?

java - 获取键盘输入并用于变量事件

java - 如何保持多个 Java HttpConnections 打开到同一个目的地

java - Android应用程序搜索下载文件夹中的特定文件

Android 下载管理器和 SSL (https)

android - DownloadManager.ACTION_DOWNLOAD_COMPLETE 广播接收器在 Android 中多次接收相同的下载 ID,但下载状态不同

java - 如何洗牌存储在数组中的一副牌?