开发者

How to enable Https Downloads using java

I use following code to download...

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);  //r开发者_开发技巧eading in Buffer

        if(read==-1)
           break;

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

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


}

I am using above code to download a file from URL in loops. I am using InputStream from downloading(reading). Should i use Channels to improve performance ?

Please guide me by watching my code to enhance downloading speed.


Wrap the InputStream with a BufferedInputStream and increase the buffer size. Switching to a channel implementation wouldn't improve much on the client side, even if it's rather good to use on the server side.

You should also only create one byte[] and reuse it. Don't create it each iteration in the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜