HttpURLConnection继承了URLConnection,因此也可用于向指定网站发送GET请求、POST请求,而且它在URLConnection基础上提供了如下便捷方法:

实现多线程下载的步骤:

下面用一个示例来示范使用HttpURLConnection实现多线程下载。此代码来源疯狂讲义一书,该代码主要思路:在Activity中点击按钮,调用DownUtil的download()方法,在download()中启动四个线程去下载资源,每个线程负责下载自己的那部分资源,代码如下:

Activity:

package com.home.activity;

import java.util.Timer;
import java.util.TimerTask; import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar; import com.home.multithreaddown.R;
import com.home.util.DownUtil; public class MultiThreadDownActivity extends Activity {
private EditText urlText;
private EditText targetText;
private Button downBtn;
private ProgressBar bar;
private DownUtil downUtil;
private int mDownStatus;
private Handler handler; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取界面中控件
targetText = (EditText) findViewById(R.id.main_et_name);
urlText = (EditText) findViewById(R.id.main_et_url);
downBtn = (Button) findViewById(R.id.main_btn_download);
bar = (ProgressBar) findViewById(R.id.main_progressBar);
// 创建一个Handler对象
handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
bar.setProgress(mDownStatus);
}
}
};
downBtn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// 初始化DownUtil对象
downUtil = new DownUtil(urlText.getText().toString(),
targetText.getText().toString(), 4);
try {
// 开始下载
downUtil.download();
} catch (Exception e) {
e.printStackTrace();
}
// 定义每秒调度获取一次系统的完成进度
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// 获取下载任务的完成比率
double completeRate = downUtil.getCompleteRate();
mDownStatus = (int) (completeRate * 100);
// 发送消息通知界面更新进度条
handler.sendEmptyMessage(0x123);
// 下载完成后取消任务调度
if (mDownStatus >= 100) {
timer.cancel();
}
}
}, 0, 100); }
});
} }

下载的工具类(DownUtil):

package com.home.util;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL; public class DownUtil {
// 定义下载资源的路径
private String path;
// 指定所下载的文件的保存位置
private String targetFile;
// 定义需要使用多少线程下载资源
private int threadNum;
// 定义下载的文件的总大小
private int fileSize;
// 定义下载的线程对象
private DownloadThread[] threads; public DownUtil(String path, String targetFile, int threadNum) {
this.path = path;
this.threadNum = threadNum;
// 初始化threads数组
threads = new DownloadThread[threadNum];
this.targetFile = targetFile;
} public void download() throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
conn.setRequestProperty(
"Accept",
"image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/x-ms-xbap,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0(compatible;MSIE7.0;Windows NT 5.2;Trident/4.0;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30;.NET CLR 3.0.4506.2152;.NET CLR 3.5.30729)"); conn.setRequestProperty("Connection", "Keep-Alive");
// 得到文件大小
fileSize = conn.getContentLength();
conn.disconnect();
int currentPartSize = fileSize / threadNum + 1;
RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
// 设置本地文件的大小
file.setLength(fileSize);
file.close();
for (int i = 0; i < threadNum; i++) {
// 计算每条线程的下载的开始位置
int startPos = i * currentPartSize;
// 每个线程使用一个RandomAccessFile进行下载
RandomAccessFile currentPart = new RandomAccessFile(targetFile,
"rw");
// 定位该线程的下载位置
currentPart.seek(startPos);
// 创建下载线程
threads[i] = new DownloadThread(startPos, currentPartSize,
currentPart);
// 启动下载线程
threads[i].start();
}
} /**
* 获取下载完成的百分比
*
* @return
*/
public double getCompleteRate() {
// 统计多条线程已经下载的总大小
int sumSize = 0;
for (int i = 0; i < threadNum; i++) {
sumSize += threads[i].length;
}
// 返回已经完成的百分比
return sumSize * 1.0 / fileSize;
} private class DownloadThread extends Thread {
// 当前线程的下载位置
private int startPos;
// 定义当前线程负责下载的文件大小
private int currentPartSize;
// 当前线程需要下载的文件块
private RandomAccessFile currentPart;
// 定义该线程已下载的字节数
private int length = 0; public DownloadThread(int startPos, int currentPartSize,
RandomAccessFile currentPart) {
this.startPos = startPos;
this.currentPartSize = currentPartSize;
this.currentPart = currentPart;
} public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
conn.setRequestProperty(
"Accept",
"image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/x-ms-xbap,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("Charset", "UTF-8");
InputStream is = conn.getInputStream();
// 跳过startPos个字符,表明该线程只下载自己负责那部分文件
is.skip(startPos);
byte[] by = new byte[1024];
int hasRead = 0;
// 读取网络数据,并写入本地文件
while (length < currentPartSize
&& (hasRead = is.read(by)) != -1) {
currentPart.write(by, 0, hasRead);
// 累计该线程下载的总大小
length += hasRead;
}
currentPart.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Activity布局XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="输入url:" /> <EditText
android:id="@+id/main_et_url"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="输入保存的文件名:" /> <EditText
android:id="@+id/main_et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout> <Button
android:id="@+id/main_btn_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载" /> <ProgressBar
android:id="@+id/main_progressBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> </LinearLayout>

权限:

<!-- 在SD卡中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 向SD卡写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 授权访问网络 -->
<uses-permission android:name="android.permission.INTERNET"/>

使用HttpURLConnection实现多线程下载的更多相关文章

  1. java 多线程下载文件 以及URLConnection和HttpURLConnection的区别

    使用 HttpURLConnection 实现多线程下载文件 注意GET大写//http public class MultiThreadDownload { public static void m ...

  2. 多线程下载 HttpURLConnection

    Activity /**实际开发涉及文件上传.下载都不会自己写这些代码,一般会使用第三方库(如xUtils)或Android提供的DownloadManager下载*/ public class Ht ...

  3. 使用HttpURLConnection多线程下载

    1 import java.io.IOException; 2 import java.io.InputStream; 3 import java.io.RandomAccessFile; 4 imp ...

  4. 【Java EE 学习 22 下】【单线程下载】【单线程断点下载】【多线程下载】

    一.文件下载简述 1.使用浏览器从网页上下载文件,Servlet需要增加一些响应头信息 (1)response.setContentType("application/force-downl ...

  5. Java--使用多线程下载,断点续传技术原理(RandomAccessFile)

    一.基础知识 1.什么是线程?什么是进程?它们之间的关系? 可以参考之前的一篇文章:java核心知识点学习----并发和并行的区别,进程和线程的区别,如何创建线程和线程的四种状态,什么是线程计时器 简 ...

  6. android 多线程下载 断点续传

    来源:网易云课堂Android极客班第八次作业练习 练习内容: 多线程 asyncTask handler 多线程下载的原理 首先获取到目标文件的大小,然后在磁盘上申请一块空间用于保存目标文件,接着把 ...

  7. 无废话Android之smartimageview使用、android多线程下载、显式意图激活另外一个activity,检查网络是否可用定位到网络的位置、隐式意图激活另外一个activity、隐式意图的配置,自定义隐式意图、在不同activity之间数据传递(5)

    1.smartimageview使用 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&q ...

  8. Java 仿迅雷多线程下载

    package net.webjoy.jackluo.android_json; /** * 1.http Range "bytes="+ start+end * 2.Random ...

  9. android程序---->android多线程下载(一)

    多线程下载是加快下载速度的一种方式,通过开启多个线程去执行一个任务,可以使任务的执行速度变快.多线程的任务下载时常都会使用得到断点续传下载,就是我们在一次下载未结束时退出下载,第二次下载时会接着第一次 ...

随机推荐

  1. SQL编程之生日问题

    在学习MySQL的时候,一个较为经典的SQL编程题目就是生日问题,已知某个用户的出生日期和当前日期,计算他近期的生日. 一般须要考虑两个问题 闰年2月是29天 今年的生日是否过完 比如:某人的生日是1 ...

  2. 关于springmvc 方法注解拦截器的解决方案,多用于方法的鉴权

    最近在用SpringMvc写项目的时候,遇到一个问题,就是方法的鉴权问题,这个问题弄了一天了终于解决了,下面看下解决方法 项目需求:需要鉴权的地方,我只需要打个标签即可,比如只有用户登录才可以进行的操 ...

  3. EasyUI的后台界面

    EasyUI的后台界面搭建及极致重构 〇.前言 要了解一个东西长什么样,至少得让我们能看到,才能提出针对性的见解.所以,为了言之有物,而不是凭空漫谈,我们先从UI说起,后台管理页面的UI我们将使用应用 ...

  4. IIS服务器 远程发布(Web Deploy)配置 VS2010 开发环境 Windows Server 2008服务器系统

    原文:IIS服务器 远程发布(Web Deploy)配置 VS2010 开发环境 Windows Server 2008服务器系统 asp.net 网站有三种常用的发布方式:分别是拷贝开发机上发布好的 ...

  5. PHP 18:data_valid_fns.php 看正则表达式

    原文:PHP 18:data_valid_fns.php 看正则表达式 本章介绍正则表达式.先看看data_valid_fns.php的代码吧.                 简要介绍一下.fill ...

  6. 用lucene.net根据关键字检索本地word文档

    目前在做一个winform小软件,其中有一个功能是能根据关键字检索本地保存的word文档.第一次是用com读取word方式(见上一篇文章),先遍历文件夹下的word文档,读取每个文档时循环关键字查找, ...

  7. iOS基础 - 多媒体

    一.播放视频 iOS提供了叫做MPMoviePlayerController.MPMoviePlayerViewController的两个类,可以用来轻松播放视频 YouTobe就是用MPMovieP ...

  8. RoleManager 进行角色管理

    ASP.NET Identity 使用 RoleManager 进行角色管理 (VS2013RC) 注:本文系作者原创,但可随意转载. 最近做一个Web平台系统,系统包含3个角色,“管理员, 企业用户 ...

  9. ASP.NET中页面传值

    一.目前在ASP.NET中页面传值共有这么几种方式: 1.表单提交,    <form action= "target.aspx" method = "post&q ...

  10. C51编译器扩展的关键词 & C51中断函数的写法

    C51根据单片机的特性扩展了相关的关键字,如下表示: 关键词 用途 说明 bit 位变量声明 声明了一个位变量或者位类型的函数 sbit 位变量声明 声明了一个可位寻址变量 sfr 特殊功能寄存器声明 ...