如何使用java启用Https下载
我使用以下代码下载如何使用java启用Https下载,java,httpurlconnection,download-manager,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
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。我应该使用频道来提高性能吗
请通过观看我的代码来指导我提高下载速度。使用
BufferedInputStream
包装InputStream
,并增加缓冲区大小。切换到通道实现在客户端不会有多大改进,即使在服务器端使用它也很好
您还应该只创建一个
字节[]
并重用它。不要在循环中每次迭代创建它。如何启用HTTPS下载,与您的问题有关?请考虑使用类似HTTPclipse的东西。与HttpURLConnection相比,它功能更强大,值得学习抽象,而且错误更少