如何使用 java 启用 Https 下载
我使用下面的代码来下载...
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。我应该使用通道来提高性能吗?
请指导我观看我的代码以提高下载速度。
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); //reading 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
BufferedInputStream
包装InputStream
并增加缓冲区大小。切换到通道实现不会对客户端有太大改进,即使在服务器端使用起来相当好。您还应该只创建一个
byte[]
并重复使用它。不要在循环中的每次迭代中创建它。Wrap the
InputStream
with aBufferedInputStream
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.