Http通信模仿迅雷多线程下载
来源:互联网 发布:zoomla 逐浪cms 编辑:程序博客网 时间:2024/04/29 13:16
转载请注明出处:http://blog.csdn.net/wei_chong_chong/article/details/51555388
用到的知识点:
1.Http 协议字段"Range", "bytes="+start+"-"+end
2.RandomAccessFile设置写入的位置
3.开启线程发送网络请求以及线程池操作
首先,在服务器端放一张图片,如下在WebRoot下放置了一张lufei.jpg图片
跟访问网页一样通过url直接访问:http://pc-20141102midc:8080/DownLoadFile/lufei.jpg
然后在Android端写多线程下载的代码:
为了防止遗忘现在配置文件中声明权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.download_file.MainActivity" > <Button android:id="@+id/start_download_bt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="下载" android:textColor="@android:color/background_dark" /> <TextView android:id="@+id/my_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /></LinearLayout>
下载类:
DownLoad.javapackage com.example.download_file;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.concurrent.Executor;import java.util.concurrent.Executors;import android.os.Environment;import android.os.Handler;import android.os.Message;/** * 多线程下载例子 * @author weichongchong * */public class DownLoad {private Handler mHandler;public DownLoad(Handler handle){this.mHandler= handle;}//通过线程池下载,创建线程池对象private Executor threadPool = Executors.newFixedThreadPool(3);//创建三个线程池static class DownLoadRunnable implements Runnable{private String url;private String fileName;private long start;private long end;private Handler handler;public DownLoadRunnable(String url ,String fileName,long start,long end,Handler handler ){this.url=url;this.fileName = fileName;this.start = start;this.end = end;this.handler= handler;}@Overridepublic void run() {// TODO Auto-generated method stubtry {URL httpUrl = new URL(url);HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();conn.setReadTimeout(5000);conn.setRequestProperty("Range", "bytes="+start+"-"+end);//指定长度conn.setRequestMethod("GET");//创建随机读取流进行读取RandomAccessFile access = new RandomAccessFile(new File(fileName), "rwd");//第二个参数代表可读,可写,可执行access.seek(start);InputStream in = conn.getInputStream();byte[] b = new byte[1024*4];int len=0;while((len = in.read())!=-1){access.write(b,0,len);}if(access!=null){access.close();}if(in!=null){in.close();}//下载完成通知更新UIMessage message = new Message();message.what=1;handler.sendMessage(message);//int count = conn.getContentLength();//拿到下载对象的长度//int block = count/3;//平均到每个线程池} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void downLoadFile(String url){try {URL httpUrl = new URL(url);HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();conn.setReadTimeout(5000);conn.setRequestMethod("GET");int count = conn.getContentLength();//拿到下载对象的长度int block = count/3;//平均到每个线程池String fileName = getFileName(url);//File parent = Environment.getExternalStorageDirectory();//File fileDownLoad = new File(parent,fileName);File fileDownLoad = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),fileName);/** * 11/3 3 * 第一个线程0-2 * 第二个3-5 * 第三个6-10 */for(int i=0;i<3;i++){long start = i*block;long end = (i+1)*block-1;if(i==2){end=count;}DownLoadRunnable runnable = new DownLoadRunnable(url,fileDownLoad.getAbsolutePath(),start,end,mHandler);threadPool.execute(runnable);//通过线程池提交任务}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * * @return * 得到url后缀名,即文件名 */public String getFileName(String url){return url.substring(url.lastIndexOf("/")+1);}}
MainActivity中代码使用下载类进行下载
package com.example.download_file;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {private Button start_download_bt;private TextView mytv;private int count = 0;private Handler mHandler = new Handler(){public void handleMessage(android.os.Message msg) {int result = msg.what;count+=result;//如果三个线程都下载完成,都返回一个1,相加为3if(count==3){mytv.setText("下载完成");start_download_bt.setText("下载完成");}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);start_download_bt = (Button) findViewById(R.id.start_download_bt);mytv = (TextView) findViewById(R.id.my_tv);start_download_bt.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubstart_download_bt.setText("正在下载");Toast.makeText(MainActivity.this, "正在下载", 0).show();new Thread(){@Overridepublic void run() {// TODO Auto-generated method stubDownLoad mDownLoad = new DownLoad(mHandler);mDownLoad.downLoadFile("http://192.168.1.105:8080/DownLoadFile/lufei.jpg");}}.start();}});}}
1 0
- Http通信模仿迅雷多线程下载
- 模拟迅雷下载程序 多线程
- HTTP 单线程 模拟迅雷下载
- http多线程下载
- http多线程下载
- http:多线程下载器
- Http多线程下载
- HTTP多线程下载文件
- http协议多线程下载
- Http多线程下载
- 迅雷多线程
- 利用多线程实现的下载器,完爆迅雷!
- 多线程:使用ImageView下载图片(模仿 SDWebImage)
- 多线程:使用ImageView分类下载图片(模仿 SDWebImage)
- java实现http多线程下载
- Android http 多线程下载心得
- Android中http多线程下载
- C# Http多线程下载、断点续传
- Linux 输入设备驱动上报按键值方法
- 程序员必备神器
- leetcode345
- IT女性的职业困惑 (1)
- java中Array/List/Map/Object与Json互相转换详解
- Http通信模仿迅雷多线程下载
- time类中的运算符重载
- HDU - 4002 Find the maximum (Java大数打表)
- 关于JSONArray:JSONArray jsonArray=JSONArray.fromObject(list)不执行!
- C001-C语言-语法与用法摘录-(ques=2)
- 实现分数类中的对象和整型数的四则运算。分数类中的对象可以和整型数进行四则运算,且运算符合交换律。例如:CFraction a(1,3),b; int i=2; 可以完成b=a+i;。同样,可以完成i+
- IT女性的职业困惑 (2)
- Android学习笔记(十三)text 文本输入
- debian8.5(jessie)安装docker