openConnection
方法创建连接对象。(HttpURLConnection conn = (HttpURLConnection)new URL("网址").openConnection();)setRequestProperty()
)connect
方法建立到远程对象的实际连接。(conn.connect())getHeaderField(),conn.getInputStream等方法对连接进行操作
)下面是对文件下载的具体实现案例(单线程):
HttpURLConnection conn = (HttpURLConnection)new URL("资源网址").openConnection();
conn.connect();
InputStream is = connection.getInputStream();
FileOutputStream os = new FileOutputStream("保存路径");
int count = 1024;
if(connection.getResponseCode()==200){
while ((count = is.read(b))!=-1) {
os.write(b,0,count);
}
os.close();
is.close();
}
多线程要设置的头文件:connection.setRequestProperty("Range", "bytes=0-4194304");
/*
有个疑惑:
代码这样写的话,出现文件下载不全。
while (count==1024) {
count = is.read(b)
os.write(b,0,count);
}
*/
原文:http://www.cnblogs.com/wbjgogogo/p/4949803.html