Android应用开发:网络编程-2

Bertha 。 2022-09-27 12:30 271阅读 0赞

网络编程

  • Java基础:网络编程
  • Uri、URL、UriMatcher、ContentUris详解
  • Android应用开发:网络编程1
  • Android应用开发:网络编程2

1. 使用HttpClient发送get请求

HttpClient是Apache开发的第三方框架,Google把它封装到了Android API中,用于发送HTTP请求。

在Android.jar包中,可以看到有很多java的API,这些都是被Android改写的API,也可以看到Android封装了大量的Apache API。

img

img

img

示例:res\layout\activity_main.xml

  1. <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" tools:context=".MainActivity" android:orientation="vertical">
  2. <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content"/>
  3. <EditText android:id="@+id/et_pass" android:layout_width="match_parent" android:layout_height="wrap_content"/>
  4. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="get登陆" android:onClick="click1" />
  5. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="post登陆" android:onClick="click2" />
  6. </LinearLayout>

src/cn.itcast.getmethod/MainActivity.java

  1. package cn.itcast.getmethod;
  2. import java.io.InputStream;
  3. import java.net.URLEncoder;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.StatusLine;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.os.Handler;
  13. import android.os.Message;
  14. import android.view.View;
  15. import android.widget.EditText;
  16. import android.widget.Toast;
  17. import cn.itcast.getmethod.tool.Tools;
  18. public class MainActivity extends Activity {
  19. Handler handler = new Handler(){
  20. @Override
  21. public void handleMessage(Message msg) {
  22. Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
  23. }
  24. };
  25. @Override
  26. protected void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_main);
  29. }
  30. public void click1(View v){
  31. EditText et_name = (EditText)findViewById(R.id.et_name);
  32. EditText et_pass = (EditText)findViewById(R.id.et_pass);
  33. String name = et_name.getText().toString();
  34. String pass = et_pass.getText().toString();
  35. final String path = "http://192.168.1.100:8080/Web/servlet/Login?name="
  36. + URLEncoder.encode(name) + "&pass=" + pass;
  37. Thread t = new Thread(){
  38. @Override
  39. public void run() {
  40. //1. 创建客户端对象
  41. //HttpClient是一个接口,不要new一个HttpClient对象,否则要实现很多的方法
  42. HttpClient client = new DefaultHttpClient();
  43. //2. 创建Http GET请求对象
  44. HttpGet get = new HttpGet(path);
  45. try {
  46. //3. 使用客户端发送get请求
  47. HttpResponse response = client.execute(get);
  48. //获取状态行
  49. StatusLine line = response.getStatusLine();
  50. //从状态行中拿到状态码
  51. if(line.getStatusCode() == 200){
  52. //获取实体,实体里存放的是服务器返回的数据的相关信息
  53. HttpEntity entity = response.getEntity();
  54. //获取服务器返回的输入流
  55. InputStream is = entity.getContent();
  56. String text = Tools.getTextFromStream(is);
  57. //发送消息,让主线程刷新UI
  58. Message msg = handler.obtainMessage();
  59. msg.obj = text;
  60. handler.sendMessage(msg);
  61. }
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. };
  67. t.start();
  68. }
  69. }

添加权限:

img

点击get登陆按钮,运行结果:

img

2. 使用HttpClient发送post请求

src/cn.itcast.postmethod/MainActivity.java

  1. package cn.itcast.postmethod;
  2. import java.io.InputStream;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.NameValuePair;
  8. import org.apache.http.StatusLine;
  9. import org.apache.http.client.HttpClient;
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13. import org.apache.http.message.BasicNameValuePair;
  14. import android.app.Activity;
  15. import android.os.Bundle;
  16. import android.os.Handler;
  17. import android.os.Message;
  18. import android.view.View;
  19. import android.widget.EditText;
  20. import android.widget.Toast;
  21. import cn.itcast.getmethod.R;
  22. import cn.itcast.getmethod.tool.Tools;
  23. public class MainActivity extends Activity {
  24. Handler handler = new Handler(){
  25. @Override
  26. public void handleMessage(Message msg) {
  27. Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
  28. }
  29. };
  30. @Override
  31. protected void onCreate(Bundle savedInstanceState) {
  32. super.onCreate(savedInstanceState);
  33. setContentView(R.layout.activity_main);
  34. }
  35. public void click2(View v){
  36. EditText et_name = (EditText)findViewById(R.id.et_name);
  37. EditText et_pass = (EditText)findViewById(R.id.et_pass);
  38. final String name = et_name.getText().toString();
  39. final String pass = et_pass.getText().toString();
  40. final String path = "http://:8080/Web/servlet/Login";
  41. Thread t = new Thread(){
  42. @Override
  43. public void run() {
  44. //1. 创建客户端对象
  45. HttpClient client = new DefaultHttpClient();
  46. //2. 创建Http POST请求对象
  47. HttpPost post = new HttpPost(path);
  48. try{
  49. //通过此集合封装要提交的数据
  50. List<NameValuePair> parameters = new ArrayList<NameValuePair>();
  51. //集合的泛型是BasicNameValuePair类型,那么由此可以推算出,要提交的数据是封装在BasicNameValuePair对象中
  52. BasicNameValuePair bvp1 = new BasicNameValuePair("name", name);
  53. BasicNameValuePair bvp2 = new BasicNameValuePair("pass", pass);
  54. parameters.add(bvp1);
  55. parameters.add(bvp2);
  56. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");
  57. //把实体类封装至post请求中,提交post请求时,实体中的数据就会用输出流写给服务器
  58. post.setEntity(entity);
  59. //客户端发送post请求
  60. HttpResponse response = client.execute(post);
  61. //获取状态行
  62. StatusLine line = response.getStatusLine();
  63. //从状态行中拿到状态码
  64. if(line.getStatusCode() == 200){
  65. //获取实体,实体里存放的是服务器返回的数据的相关信息
  66. HttpEntity et = response.getEntity();
  67. //获取服务器返回的输入流
  68. InputStream is = et.getContent();
  69. String text = Tools.getTextFromStream(is);
  70. //发送消息,让主线程刷新UI
  71. Message msg = handler.obtainMessage();
  72. msg.obj = text;
  73. handler.sendMessage(msg);
  74. }
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. };
  80. t.start();
  81. }
  82. }

点击post登陆按钮,运行结果:

img

3. 异步HttpClient框架

从github上下载android-async-http-master开源jar包,拷贝library/src/main/java目录下的内容到我们自己的项目中。

img

img

拷贝后,发现有错误,这是由于Base64.java中的BuildConfig类导包问题,Ctrl+Shift+O自动导包即可修复。

img

img

img

使用异步HttpClient框架实现上面示例中的功能,activity.xml与上面的示例相同,修改MainActivity.java代码。
src/cn.itcast.asynchttpclient/MainActivity.java

  1. package cn.itcast.asynchttpclient;
  2. import org.apache.http.Header;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.EditText;
  7. import android.widget.Toast;
  8. import com.loopj.android.http.AsyncHttpClient;
  9. import com.loopj.android.http.AsyncHttpResponseHandler;
  10. import com.loopj.android.http.RequestParams;
  11. public class MainActivity extends Activity {
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. }
  17. public void click1(View v){
  18. EditText et_name = (EditText)findViewById(R.id.et_name);
  19. EditText et_pass = (EditText)findViewById(R.id.et_pass);
  20. final String name = et_name.getText().toString();
  21. final String pass = et_pass.getText().toString();
  22. final String path = "http://192.168.1.100:8080/Web/servlet/Login";
  23. //使用异步HttpClient发送get请求
  24. AsyncHttpClient client = new AsyncHttpClient();
  25. //定义一个请求参数对象,封装要提交的数据
  26. RequestParams rp = new RequestParams();
  27. rp.add("name", name);
  28. rp.add("pass", pass);
  29. //发送get请求
  30. client.get(path, rp, new MyResponseHandler());
  31. }
  32. public void click2(View v){
  33. EditText et_name = (EditText)findViewById(R.id.et_name);
  34. EditText et_pass = (EditText)findViewById(R.id.et_pass);
  35. final String name = et_name.getText().toString();
  36. final String pass = et_pass.getText().toString();
  37. final String path = "http://192.168.1.100:8080/Web/servlet/Login";
  38. AsyncHttpClient client = new AsyncHttpClient();
  39. RequestParams rp = new RequestParams();
  40. rp.add("name", name);
  41. rp.add("pass", pass);
  42. //发送post请求
  43. client.post(path, rp, new MyResponseHandler());
  44. }
  45. class MyResponseHandler extends AsyncHttpResponseHandler{
  46. //请求成功时(响应码为200开头),此方法调用
  47. //登陆成功或者登录失败,只要请求成功,都会调用onSuccess方法
  48. @Override
  49. public void onSuccess(int statusCode, Header[] headers,
  50. byte[] responseBody) {
  51. Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
  52. }
  53. //请求失败时(响应码非200开头)调用
  54. @Override
  55. public void onFailure(int statusCode, Header[] headers,
  56. byte[] responseBody, Throwable error) {
  57. //请求不成功,也显示登录失败
  58. Toast.makeText(MainActivity.this, "登陆失败", 0).show();
  59. }
  60. }
  61. }

添加权限:

img

运行结果:分别点击“get登陆”和“post登陆”按钮。

img

4. 多线程下载的原理和过程

断点续传:上次下载到哪,这次就从哪开始下。
多线程:下载速度更快。
原理:抢占服务器资源。例如:带宽为20M/s,3个人去下载同一部电影,那么每人分别占6.66M/s带宽。如果有一人A开了3个线程同时下载,那么5个线程,各占4M/s带宽,那么A所占带宽就是4*3=12M/s,其他两人各占4M/s带宽。也就是说A抢占了更多的服务器资源。

img

多线程下载示例说明:
例如有一个10KB的文件,分成0~10,3个线程去下载,第0个线程下载0~2,也就是3KB数据,第1个线程下载3~5,也就是3KB数据,余下的6~9,4KB的数据由最后一个线程下载。

总结出公式就是:
每个线程下载的数据开始点:threadId*size,结束点:(threadId + 1) * size -1。

最后一个线程除外,下载结束点:length - 1。

计算每条线程的下载区间

多线程断点续传的API全部都是Java API,Java项目测试比较容易,所以,我们先创建一个Java项目。
将待下载的资源放入Tomcat服务器中。

img

img

src/cn.itcast.MultiDownLoad/Main.java

  1. package cn.itcast.MultiDownLoad;
  2. import java.net.HttpURLConnection;
  3. import java.net.URL;
  4. public class Main {
  5. static int threadCount = 3;
  6. static String path = "http://localhost:8080/QQPlayer.exe";
  7. public static void main(String[] args) {
  8. URL url;
  9. try {
  10. url = new URL(path);
  11. //打开连接对象,做初始化设置
  12. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  13. conn.setConnectTimeout(8000);
  14. conn.setReadTimeout(8000);
  15. if(conn.getResponseCode() == 200){
  16. //获取要下载的目标文件的总长度
  17. int length = conn.getContentLength();
  18. //计算每条线程要下载的长度
  19. int size = length / threadCount;
  20. System.out.println("size:" + size);
  21. //计算每条线程下载的开始位置和结束位置
  22. for(int threadId = 0; threadId < threadCount; threadId++){
  23. int startIndex = threadId * size;
  24. int endIndex = (threadId + 1) * size - 1;
  25. //如果是最后一条线程,那么需要把余数也一块下载
  26. if(threadId == threadCount - 1){
  27. endIndex = length - 1;
  28. }
  29. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  30. }
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }

运行结果:

img

创建临时文件
src/cn.itcast.MultiDownLoad/Main.java

  1. package cn.itcast.MultiDownLoad;
  2. import java.io.File;
  3. import java.io.RandomAccessFile;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. public class Main {
  7. static int threadCount = 3;
  8. static String path = "http://localhost:8080/QQPlayer.exe";
  9. public static void main(String[] args) {
  10. URL url;
  11. try {
  12. url = new URL(path);
  13. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  14. conn.setConnectTimeout(8000);
  15. conn.setReadTimeout(8000);
  16. if(conn.getResponseCode() == 200){
  17. int length = conn.getContentLength();
  18. int size = length / threadCount;
  19. System.out.println("size:" + size);
  20. //创建一个与目标文件大小一致的临时文件
  21. File file = new File(getFileNameFromPath(path));
  22. //打开文件的访问模式设置为rwd,表示除了读取和写入,还要求对文件内容的每个更新都同步写入到底层存储设备。
  23. //设计到下载的程序,文件访问模式一定要使用rwd,不经过缓冲区,直接写入硬盘。
  24. //如果下载到的数据让写入到缓冲区,一旦断电,缓冲区数据丢失,并且下次服务器断点续传也不会再传输这部分数据,那么下载的文件就不能用了
  25. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  26. //设置临时文件的大小
  27. raf.setLength(length);
  28. for(int threadId = 0; threadId < threadCount; threadId++){
  29. int startIndex = threadId * size;
  30. int endIndex = (threadId + 1) * size - 1;
  31. if(threadId == threadCount - 1){
  32. endIndex = length - 1;
  33. }
  34. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  35. }
  36. }
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. public static String getFileNameFromPath(String path){
  42. int index = path.lastIndexOf("/");
  43. return path.substring(index + 1);
  44. }
  45. }

开启多个线程下载文件

src/cn.itcast.MultiDownLoad/Main.java

  1. package cn.itcast.MultiDownLoad;
  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.io.RandomAccessFile;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. public class Main {
  8. static int threadCount = 3;
  9. static String path = "http://localhost:8080/QQPlayer.exe";
  10. public static void main(String[] args) {
  11. URL url;
  12. try {
  13. url = new URL(path);
  14. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  15. conn.setConnectTimeout(8000);
  16. conn.setReadTimeout(8000);
  17. if(conn.getResponseCode() == 200){
  18. int length = conn.getContentLength();
  19. int size = length / threadCount;
  20. System.out.println("size:" + size);
  21. for(int threadId = 0; threadId < threadCount; threadId++){
  22. int startIndex = threadId * size;
  23. int endIndex = (threadId + 1) * size - 1;
  24. if(threadId == threadCount - 1){
  25. endIndex = length - 1;
  26. }
  27. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  28. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  29. dt.start();
  30. }
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. public static String getFileNameFromPath(String path){
  37. int index = path.lastIndexOf("/");
  38. return path.substring(index + 1);
  39. }
  40. }
  41. class DownLoadThread extends Thread{
  42. int threadId;
  43. int startIndex;
  44. int endIndex;
  45. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  46. super();
  47. this.threadId = threadId;
  48. this.startIndex = startIndex;
  49. this.endIndex = endIndex;
  50. }
  51. public void run(){
  52. URL url;
  53. try{
  54. url = new URL(Main.path);
  55. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  56. conn.setConnectTimeout(8000);
  57. conn.setReadTimeout(8000);
  58. //Range表示指定请求的数据区间
  59. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  60. //请求部分数据,返回的是206
  61. if(conn.getResponseCode() == 206){
  62. InputStream is = conn.getInputStream();
  63. //打开临时文件的IO流
  64. File file = new File(Main.getFileNameFromPath(Main.path));
  65. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  66. //修改写入临时文件的开始位置
  67. raf.seek(startIndex);
  68. byte[] b = new byte[1024];
  69. int len = 0;
  70. //当前线程下载的总进度
  71. int total = 0;
  72. while((len = is.read(b)) != -1){
  73. //把读取到的字节写入临时文件中
  74. raf.write(b, 0, len);
  75. total += len;
  76. System.out.println("线程" + threadId + "下载的进度为:" + total);
  77. }
  78. raf.close();
  79. }
  80. System.out.println("线程" + threadId + "下载完毕---------------------");
  81. }catch(Exception e){
  82. e.printStackTrace();
  83. }
  84. }
  85. }

运行结果:刷新,即可看到文件已经下载好了

img

img

img

img

创建进度临时文件保存下载进度

src/cn.itcast.MultiDownLoad/Main.java

  1. package cn.itcast.MultiDownLoad;
  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.io.RandomAccessFile;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. public class Main {
  8. static int threadCount = 3;
  9. static String path = "http://localhost:8080/QQPlayer.exe";
  10. public static void main(String[] args) {
  11. URL url;
  12. try {
  13. url = new URL(path);
  14. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  15. conn.setConnectTimeout(8000);
  16. conn.setReadTimeout(8000);
  17. if(conn.getResponseCode() == 200){
  18. int length = conn.getContentLength();
  19. int size = length / threadCount;
  20. System.out.println("size:" + size);
  21. for(int threadId = 0; threadId < threadCount; threadId++){
  22. int startIndex = threadId * size;
  23. int endIndex = (threadId + 1) * size - 1;
  24. if(threadId == threadCount - 1){
  25. endIndex = length - 1;
  26. }
  27. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  28. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  29. dt.start();
  30. }
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. public static String getFileNameFromPath(String path){
  37. int index = path.lastIndexOf("/");
  38. return path.substring(index + 1);
  39. }
  40. }
  41. class DownLoadThread extends Thread{
  42. int threadId;
  43. int startIndex;
  44. int endIndex;
  45. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  46. super();
  47. this.threadId = threadId;
  48. this.startIndex = startIndex;
  49. this.endIndex = endIndex;
  50. }
  51. public void run(){
  52. URL url;
  53. try{
  54. url = new URL(Main.path);
  55. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  56. conn.setConnectTimeout(8000);
  57. conn.setReadTimeout(8000);
  58. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  59. if(conn.getResponseCode() == 206){
  60. InputStream is = conn.getInputStream();
  61. File file = new File(Main.getFileNameFromPath(Main.path));
  62. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  63. raf.seek(startIndex);
  64. byte[] b = new byte[1024];
  65. int len = 0;
  66. int total = 0;
  67. while((len = is.read(b)) != -1){
  68. raf.write(b, 0, len);
  69. total += len;
  70. System.out.println("线程" + threadId + "下载的进度为:" + total);
  71. //创建一个进度临时文件,保存下载进度
  72. File fileProgress = new File(threadId + ".txt");
  73. RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
  74. rafProgress.write((total + "").getBytes());
  75. rafProgress.close();
  76. }
  77. raf.close();
  78. }
  79. System.out.println("线程" + threadId + "下载完毕---------------------");
  80. }catch(Exception e){
  81. e.printStackTrace();
  82. }
  83. }
  84. }

运行结果:执行程序,然后,在没下载完成时,就点击右上角的停止按钮。

img

刷新,可以看到记录文件已经产生。

img

img

完成断点续传下载

src/cn.itcast.MultiDownLoad/Main.java

  1. package cn.itcast.MultiDownLoad;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.RandomAccessFile;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. public class Main {
  11. static int threadCount = 3;
  12. static String path = "http://localhost:8080/QQPlayer.exe";
  13. public static void main(String[] args) {
  14. URL url;
  15. try {
  16. url = new URL(path);
  17. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  18. conn.setConnectTimeout(8000);
  19. conn.setReadTimeout(8000);
  20. if(conn.getResponseCode() == 200){
  21. int length = conn.getContentLength();
  22. int size = length / threadCount;
  23. System.out.println("size:" + size);
  24. for(int threadId = 0; threadId < threadCount; threadId++){
  25. int startIndex = threadId * size;
  26. int endIndex = (threadId + 1) * size - 1;
  27. if(threadId == threadCount - 1){
  28. endIndex = length - 1;
  29. }
  30. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  31. dt.start();
  32. }
  33. }
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. public static String getFileNameFromPath(String path){
  39. int index = path.lastIndexOf("/");
  40. return path.substring(index + 1);
  41. }
  42. }
  43. class DownLoadThread extends Thread{
  44. int threadId;
  45. int startIndex;
  46. int endIndex;
  47. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  48. super();
  49. this.threadId = threadId;
  50. this.startIndex = startIndex;
  51. this.endIndex = endIndex;
  52. }
  53. public void run(){
  54. URL url;
  55. try{
  56. int lastProgress = 0;
  57. //下载之前,先判断进度临时文件是否存在
  58. File fileProgress1 = new File(threadId + ".txt");
  59. if(fileProgress1.exists()){
  60. FileInputStream fis = new FileInputStream(fileProgress1);
  61. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  62. //读取进度临时文件中的值
  63. lastProgress = Integer.parseInt(br.readLine());
  64. //把上一次下载的进度加到下载开始位置
  65. startIndex += lastProgress;
  66. fis.close();
  67. }
  68. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  69. url = new URL(Main.path);
  70. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  71. conn.setConnectTimeout(8000);
  72. conn.setReadTimeout(8000);
  73. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  74. if(conn.getResponseCode() == 206){
  75. InputStream is = conn.getInputStream();
  76. File file = new File(Main.getFileNameFromPath(Main.path));
  77. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  78. raf.seek(startIndex);
  79. byte[] b = new byte[1024];
  80. int len = 0;
  81. //从之前下载的地方开始下载
  82. int total = lastProgress;
  83. while((len = is.read(b)) != -1){
  84. raf.write(b, 0, len);
  85. total += len;
  86. System.out.println("线程" + threadId + "下载的进度为:" + total);
  87. File fileProgress = new File(threadId + ".txt");
  88. RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
  89. rafProgress.write((total + "").getBytes());
  90. rafProgress.close();
  91. }
  92. raf.close();
  93. System.out.println("线程" + threadId + "下载完毕---------------------");
  94. }
  95. }catch(Exception e){
  96. e.printStackTrace();
  97. }
  98. }
  99. }

运行结果:

执行Main.java程序,然后,在还没有下载完,停止。然后,再次执行Main.java,可以看到如下显示,也就是实现了断点续传。

img

下载后删除进度临时文件
src/cn.itcast.MultiDownLoad/Main.java

  1. package cn.itcast.MultiDownLoad;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.RandomAccessFile;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. public class Main {
  11. //记录当前已经下载完成的线程的数量
  12. static int finishedThreadCount = 0;
  13. static int threadCount = 3;
  14. static String path = "http://localhost:8080/QQPlayer.exe";
  15. public static void main(String[] args) {
  16. URL url;
  17. try {
  18. url = new URL(path);
  19. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  20. conn.setConnectTimeout(8000);
  21. conn.setReadTimeout(8000);
  22. if(conn.getResponseCode() == 200){
  23. int length = conn.getContentLength();
  24. int size = length / threadCount;
  25. System.out.println("size:" + size);
  26. for(int threadId = 0; threadId < threadCount; threadId++){
  27. int startIndex = threadId * size;
  28. int endIndex = (threadId + 1) * size - 1;
  29. if(threadId == threadCount - 1){
  30. endIndex = length - 1;
  31. }
  32. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  33. dt.start();
  34. }
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. public static String getFileNameFromPath(String path){
  41. int index = path.lastIndexOf("/");
  42. return path.substring(index + 1);
  43. }
  44. }
  45. class DownLoadThread extends Thread{
  46. int threadId;
  47. int startIndex;
  48. int endIndex;
  49. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  50. super();
  51. this.threadId = threadId;
  52. this.startIndex = startIndex;
  53. this.endIndex = endIndex;
  54. }
  55. public void run(){
  56. URL url;
  57. try{
  58. int lastProgress = 0;
  59. File fileProgress1 = new File(threadId + ".txt");
  60. if(fileProgress1.exists()){
  61. FileInputStream fis = new FileInputStream(fileProgress1);
  62. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  63. lastProgress = Integer.parseInt(br.readLine());
  64. startIndex += lastProgress;
  65. fis.close();
  66. }
  67. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  68. url = new URL(Main.path);
  69. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  70. conn.setConnectTimeout(8000);
  71. conn.setReadTimeout(8000);
  72. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  73. if(conn.getResponseCode() == 206){
  74. InputStream is = conn.getInputStream();
  75. File file = new File(Main.getFileNameFromPath(Main.path));
  76. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  77. raf.seek(startIndex);
  78. byte[] b = new byte[1024];
  79. int len = 0;
  80. int total = lastProgress;
  81. while((len = is.read(b)) != -1){
  82. raf.write(b, 0, len);
  83. total += len;
  84. System.out.println("线程" + threadId + "下载的进度为:" + total);
  85. File fileProgress = new File(threadId + ".txt");
  86. RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
  87. rafProgress.write((total + "").getBytes());
  88. rafProgress.close();
  89. }
  90. raf.close();
  91. System.out.println("线程" + threadId + "下载完毕---------------------");
  92. //在所有线程都下载完毕后,一起删除所有进度临时文件
  93. //有一个线程完成下载,已经下载完成的线程的数量+1
  94. Main.finishedThreadCount++;
  95. synchronized(Main.path){
  96. if(Main.finishedThreadCount == 3){
  97. //删除所有进度临时文件
  98. for(int i = 0; i < Main.finishedThreadCount; i++){
  99. File f = new File(i + ".txt");
  100. f.delete();
  101. }
  102. //为了防止所有线程都执行到上面的Main.finishedThreadCount++;,然后三个线程都执行删除所有临时文件的代码。
  103. //所以,一方面使用同步代码块,另一方面将Main.finishedThreadCount设置为0。
  104. Main.finishedThreadCount = 0;
  105. }
  106. }
  107. }
  108. }catch(Exception e){
  109. e.printStackTrace();
  110. }
  111. }
  112. }

运行结果:运行Main.java,断点续传完成后,刷新。可以看到,临时文件已经被删除。

img

5. Android版多线程断点续传下载

res/layout/activity.xml

  1. <RelativeLayout 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" tools:context=".MainActivity" >
  2. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" android:onClick="click" />
  3. </RelativeLayout>

src/cn.itcast.androidmultidownload/MainActivity.xml

  1. package cn.itcast.androidmultidownload;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.RandomAccessFile;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.os.Environment;
  13. import android.view.View;
  14. public class MainActivity extends Activity {
  15. int finishedThreadCount = 0;
  16. int threadCount = 3;
  17. String path = "http://192.168.1.100:8080/QQPlayer.exe";
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_main);
  22. }
  23. public void click(View v){
  24. Thread t = new Thread(){
  25. @Override
  26. public void run() {
  27. URL url;
  28. try {
  29. url = new URL(path);
  30. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  31. conn.setConnectTimeout(8000);
  32. conn.setReadTimeout(8000);
  33. if(conn.getResponseCode() == 200){
  34. int length = conn.getContentLength();
  35. int size = length / threadCount;
  36. System.out.println("size:" + size);
  37. for(int threadId = 0; threadId < threadCount; threadId++){
  38. int startIndex = threadId * size;
  39. int endIndex = (threadId + 1) * size - 1;
  40. if(threadId == threadCount - 1){
  41. endIndex = length - 1;
  42. }
  43. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  44. dt.start();
  45. }
  46. }
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. };
  52. t.start();
  53. }
  54. public String getFileNameFromPath(String path){
  55. int index = path.lastIndexOf("/");
  56. return path.substring(index + 1);
  57. }
  58. class DownLoadThread extends Thread{
  59. int threadId;
  60. int startIndex;
  61. int endIndex;
  62. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  63. super();
  64. this.threadId = threadId;
  65. this.startIndex = startIndex;
  66. this.endIndex = endIndex;
  67. }
  68. public void run(){
  69. URL url;
  70. try{
  71. int lastProgress = 0;
  72. //修改文件路径,存在外部存储器中
  73. File fileProgress1 = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  74. if(fileProgress1.exists()){
  75. FileInputStream fis = new FileInputStream(fileProgress1);
  76. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  77. lastProgress = Integer.parseInt(br.readLine());
  78. startIndex += lastProgress;
  79. fis.close();
  80. }
  81. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  82. url = new URL(path);
  83. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  84. conn.setConnectTimeout(8000);
  85. conn.setReadTimeout(8000);
  86. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  87. if(conn.getResponseCode() == 206){
  88. InputStream is = conn.getInputStream();
  89. File file = new File(Environment.getExternalStorageDirectory(), getFileNameFromPath(path));
  90. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  91. raf.seek(startIndex);
  92. byte[] b = new byte[1024];
  93. int len = 0;
  94. int total = lastProgress;
  95. while((len = is.read(b)) != -1){
  96. raf.write(b, 0, len);
  97. total += len;
  98. System.out.println("线程" + threadId + "下载的进度为:" + total);
  99. File fileProgress = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  100. RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
  101. rafProgress.write((total + "").getBytes());
  102. rafProgress.close();
  103. }
  104. raf.close();
  105. System.out.println("线程" + threadId + "下载完毕---------------------");
  106. finishedThreadCount++;
  107. synchronized(path){
  108. if(finishedThreadCount == 3){
  109. for(int i = 0; i < finishedThreadCount; i++){
  110. File f = new File(Environment.getExternalStorageDirectory(), i + ".txt");
  111. f.delete();
  112. }
  113. finishedThreadCount = 0;
  114. }
  115. }
  116. }
  117. }catch(Exception e){
  118. e.printStackTrace();
  119. }
  120. }
  121. }
  122. }

添加权限:
img

运行结果:点击“下载”按钮,在下载完成之前,杀死线程。

img

img

可以看到临时文件生成。
img

img

再次运行应用程序,点击“下载”按钮,接着下载,断点续传成功实现。

img

下载完成后,可以看到临时文件删除成功。

img

添加进度条反应下载进度,res/layout/activity.xml

  1. <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" tools:context=".MainActivity" android:orientation="vertical">
  2. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" android:onClick="click" />
  3. <ProgressBar android:id="@+id/pb" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" />
  4. </LinearLayout>

src/cn.itcast.androidmultidownload/MainActivity.xml

  1. package cn.itcast.androidmultidownload;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.RandomAccessFile;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.os.Environment;
  13. import android.view.View;
  14. import android.widget.ProgressBar;
  15. public class MainActivity extends Activity {
  16. int finishedThreadCount = 0;
  17. int threadCount = 3;
  18. String path = "http://192.168.1.100:8080/QQPlayer.exe";
  19. private ProgressBar pb;
  20. //记录进度条的当前进度
  21. int currentProgress = 0;
  22. @Override
  23. protected void onCreate(Bundle savedInstanceState) {
  24. super.onCreate(savedInstanceState);
  25. setContentView(R.layout.activity_main);
  26. //进度条
  27. pb = (ProgressBar) findViewById(R.id.pb);
  28. }
  29. public void click(View v){
  30. Thread t = new Thread(){
  31. @Override
  32. public void run() {
  33. URL url;
  34. try {
  35. url = new URL(path);
  36. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  37. conn.setConnectTimeout(8000);
  38. conn.setReadTimeout(8000);
  39. if(conn.getResponseCode() == 200){
  40. int length = conn.getContentLength();
  41. //设定进度条的最大值
  42. pb.setMax(length);
  43. int size = length / threadCount;
  44. System.out.println("size:" + size);
  45. for(int threadId = 0; threadId < threadCount; threadId++){
  46. int startIndex = threadId * size;
  47. int endIndex = (threadId + 1) * size - 1;
  48. if(threadId == threadCount - 1){
  49. endIndex = length - 1;
  50. }
  51. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  52. dt.start();
  53. }
  54. }
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. };
  60. t.start();
  61. }
  62. public String getFileNameFromPath(String path){
  63. int index = path.lastIndexOf("/");
  64. return path.substring(index + 1);
  65. }
  66. class DownLoadThread extends Thread{
  67. int threadId;
  68. int startIndex;
  69. int endIndex;
  70. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  71. super();
  72. this.threadId = threadId;
  73. this.startIndex = startIndex;
  74. this.endIndex = endIndex;
  75. }
  76. public void run(){
  77. URL url;
  78. try{
  79. int lastProgress = 0;
  80. File fileProgress1 = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  81. if(fileProgress1.exists()){
  82. FileInputStream fis = new FileInputStream(fileProgress1);
  83. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  84. lastProgress = Integer.parseInt(br.readLine());
  85. startIndex += lastProgress;
  86. //如果开始位置大于或等于endIndex,说明上一次下载中,此线程就已经下载完了
  87. if(startIndex >= endIndex){
  88. finishedThreadCount++;
  89. }
  90. //如果上一次下载过,把上次的进度加到当前进度中
  91. currentProgress += lastProgress;
  92. pb.setProgress(currentProgress);
  93. fis.close();
  94. }
  95. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  96. url = new URL(path);
  97. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  98. conn.setConnectTimeout(8000);
  99. conn.setReadTimeout(8000);
  100. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  101. if(conn.getResponseCode() == 206){
  102. InputStream is = conn.getInputStream();
  103. File file = new File(Environment.getExternalStorageDirectory(), getFileNameFromPath(path));
  104. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  105. raf.seek(startIndex);
  106. byte[] b = new byte[1024];
  107. int len = 0;
  108. int total = lastProgress;
  109. while((len = is.read(b)) != -1){
  110. raf.write(b, 0, len);
  111. total += len;
  112. System.out.println("线程" + threadId + "下载的进度为:" + total);
  113. File fileProgress = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  114. RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
  115. rafProgress.write((total + "").getBytes());
  116. rafProgress.close();
  117. //每一条线程下载的数据,都应该加到全局进度里
  118. currentProgress += len;
  119. //设置进度条当前进度
  120. //进度条内部也是通过handler让主线程刷新UI的
  121. pb.setProgress(currentProgress);
  122. }
  123. raf.close();
  124. System.out.println("线程" + threadId + "下载完毕---------------------");
  125. finishedThreadCount++;
  126. synchronized(path){
  127. if(finishedThreadCount == 3){
  128. for(int i = 0; i < finishedThreadCount; i++){
  129. File f = new File(Environment.getExternalStorageDirectory(), i + ".txt");
  130. f.delete();
  131. }
  132. finishedThreadCount = 0;
  133. }
  134. }
  135. }
  136. }catch(Exception e){
  137. e.printStackTrace();
  138. }
  139. }
  140. }
  141. }

运行结果:点击“下载”按钮,可以通过进度条看到下载进度。然后,杀死进程,再重新运行应用程序,点击“下载”按钮,可以看到进度条在原有的基础上继续向前移动,也就是实现了断点续传的进度条实现。

img

添加文本进度,res/layout/activity.xml

  1. <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" tools:context=".MainActivity" android:orientation="vertical">
  2. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" android:onClick="click" />
  3. <ProgressBar android:id="@+id/pb" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" />
  4. <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0%" android:layout_gravity="right" />
  5. </LinearLayout>

src/cn.itcast.androidmultidownload/MainActivity.xml

  1. package cn.itcast.androidmultidownload;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.RandomAccessFile;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.os.Environment;
  13. import android.os.Handler;
  14. import android.view.View;
  15. import android.widget.ProgressBar;
  16. import android.widget.TextView;
  17. public class MainActivity extends Activity {
  18. int finishedThreadCount = 0;
  19. int threadCount = 3;
  20. String path = "http://192.168.1.100:8080/QQPlayer.exe";
  21. private ProgressBar pb;
  22. int currentProgress = 0;
  23. private TextView tv;
  24. //刷新TextView
  25. Handler handler = new Handler(){
  26. public void handleMessage(android.os.Message msg) {
  27. //当前进度除以最大进度,得到下载进度的百分比
  28. tv.setText(pb.getProgress() * 100 /pb.getMax() + "%");
  29. }
  30. };
  31. @Override
  32. protected void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_main);
  35. pb = (ProgressBar) findViewById(R.id.pb);
  36. tv = (TextView)findViewById(R.id.tv);
  37. }
  38. public void click(View v){
  39. Thread t = new Thread(){
  40. @Override
  41. public void run() {
  42. URL url;
  43. try {
  44. url = new URL(path);
  45. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  46. conn.setConnectTimeout(8000);
  47. conn.setReadTimeout(8000);
  48. if(conn.getResponseCode() == 200){
  49. int length = conn.getContentLength();
  50. pb.setMax(length);
  51. int size = length / threadCount;
  52. System.out.println("size:" + size);
  53. for(int threadId = 0; threadId < threadCount; threadId++){
  54. int startIndex = threadId * size;
  55. int endIndex = (threadId + 1) * size - 1;
  56. if(threadId == threadCount - 1){
  57. endIndex = length - 1;
  58. }
  59. DownLoadThread dt = new DownLoadThread(threadId, startIndex, endIndex);
  60. dt.start();
  61. }
  62. }
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. };
  68. t.start();
  69. }
  70. public String getFileNameFromPath(String path){
  71. int index = path.lastIndexOf("/");
  72. return path.substring(index + 1);
  73. }
  74. class DownLoadThread extends Thread{
  75. int threadId;
  76. int startIndex;
  77. int endIndex;
  78. public DownLoadThread(int threadId, int startIndex, int endIndex) {
  79. super();
  80. this.threadId = threadId;
  81. this.startIndex = startIndex;
  82. this.endIndex = endIndex;
  83. }
  84. public void run(){
  85. URL url;
  86. try{
  87. int lastProgress = 0;
  88. File fileProgress1 = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  89. if(fileProgress1.exists()){
  90. FileInputStream fis = new FileInputStream(fileProgress1);
  91. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  92. lastProgress = Integer.parseInt(br.readLine());
  93. startIndex += lastProgress;
  94. if(startIndex >= endIndex){
  95. finishedThreadCount++;
  96. }
  97. currentProgress += lastProgress;
  98. pb.setProgress(currentProgress);
  99. //发送消息,让主线程刷新文本进度
  100. handler.sendEmptyMessage(1);
  101. fis.close();
  102. }
  103. System.out.println("线程" + threadId + ",下载区间为:" + startIndex + "-" + endIndex);
  104. url = new URL(path);
  105. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  106. conn.setConnectTimeout(8000);
  107. conn.setReadTimeout(8000);
  108. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  109. if(conn.getResponseCode() == 206){
  110. InputStream is = conn.getInputStream();
  111. File file = new File(Environment.getExternalStorageDirectory(), getFileNameFromPath(path));
  112. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  113. raf.seek(startIndex);
  114. byte[] b = new byte[1024];
  115. int len = 0;
  116. int total = lastProgress;
  117. while((len = is.read(b)) != -1){
  118. raf.write(b, 0, len);
  119. total += len;
  120. System.out.println("线程" + threadId + "下载的进度为:" + total);
  121. File fileProgress = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  122. RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
  123. rafProgress.write((total + "").getBytes());
  124. rafProgress.close();
  125. currentProgress += len;
  126. pb.setProgress(currentProgress);
  127. //发送消息,让主线程刷新文本进度
  128. handler.sendEmptyMessage(1);
  129. }
  130. raf.close();
  131. System.out.println("线程" + threadId + "下载完毕---------------------");
  132. finishedThreadCount++;
  133. synchronized(path){
  134. if(finishedThreadCount == 3){
  135. for(int i = 0; i < finishedThreadCount; i++){
  136. File f = new File(Environment.getExternalStorageDirectory(), i + ".txt");
  137. f.delete();
  138. }
  139. finishedThreadCount = 0;
  140. }
  141. }
  142. }
  143. }catch(Exception e){
  144. e.printStackTrace();
  145. }
  146. }
  147. }
  148. }

运行结果:

img

文本进度计算的bug:当文件较大时,就会出现bug,文本进度计算数据变成了负数。

img

这是因为文件大小超出了int所能表示的最大范围。

img

只需要修改代码如下即可。

img

如果最终显示为99%,那么只需要在下载完成之后,直接在程序中写死为100%即可。

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

从github上下载xUtils,将xUtils的jar复制到libs目录下。

img

img

如果无法关联源码,可以通过在libs目录下新建一个properties文件解决。

img

properties文件的内容为”src=源码目录”,即可成功关联源码。

img

res/layout/activity.xml

  1. <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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical" >
  2. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" android:onClick="click" />
  3. <TextView android:id="@+id/tv_success" android:layout_width="wrap_content" android:layout_height="wrap_content" />
  4. <TextView android:id="@+id/tv_failure" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" />
  5. <ProgressBar android:id="@+id/tv_pb" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" />
  6. <TextView android:id="@+id/tv_progress" android:layout_width="wrap_content" android:layout_height="wrap_content" />
  7. </LinearLayout>

src/cn.itcast.androidmultidownload/MainActivity.xml

  1. package cn.itcast.xutils;
  2. import java.io.File;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.ProgressBar;
  7. import android.widget.TextView;
  8. import com.lidroid.xutils.HttpUtils;
  9. import com.lidroid.xutils.exception.HttpException;
  10. import com.lidroid.xutils.http.HttpHandler;
  11. import com.lidroid.xutils.http.ResponseInfo;
  12. import com.lidroid.xutils.http.callback.RequestCallBack;
  13. public class MainActivity extends Activity {
  14. String path = "http://192.168.1.100:8080/QQPlayer.exe";
  15. private TextView tv;
  16. private ProgressBar pb;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. pb = (ProgressBar)findViewById(R.id.tv_pb);
  22. tv = (TextView)findViewById(R.id.tv_progress);
  23. }
  24. public void click(View v){
  25. HttpUtils utils = new HttpUtils();
  26. HttpHandler handler = utils.download(path, //请求的网址
  27. "sdcard/QQPlayer.exe", //文件保存的路径及文件名
  28. true, // 是否支持断点续传
  29. true, // 如果相应头中包含文件名,那么下载完毕后,自动以该名字重命名文件
  30. new RequestCallBack<File>() {
  31. //下载完成调用
  32. @Override
  33. public void onSuccess(ResponseInfo<File> responseInfo) {
  34. TextView tv = (TextView)findViewById(R.id.tv_success);
  35. tv.setText(responseInfo.result.getPath());
  36. }
  37. //下载失败后调用
  38. @Override
  39. public void onFailure(HttpException error, String msg) {
  40. TextView tv = (TextView)findViewById(R.id.tv_success);
  41. tv.setText(msg);
  42. }
  43. //下载过程中不断调用
  44. @Override
  45. public void onLoading(long total, long current,
  46. boolean isUploading) {
  47. pb.setMax((int)total);
  48. pb.setProgress((int)current);
  49. tv.setText((current * 100)/ total + "%");
  50. }
  51. });
  52. }
  53. }

添加权限:

img

运行结果:

img


1. 内容摘要

  • 使用HttpURLConnection 提交数据
  • 使用HttpClient 提交数据
  • 使用AsyncHttpClient 框架提交数据
  • Android 实现多线程下载
  • 使用xUtils 框架实现多线程下载

2. 前言

移动互联网时代哪个app 不需要跟服务器进行交互呢?Android 给服务器提交数据的方式都有哪些呢?这正是本文3、4、5节讨论的话题,每一节介绍一种提交数据的方式,但是Android 提交数据的方式绝非仅仅这三种,这里给出的只是最基础的3 中方式。将这些基础的方式学会了,其他再高级的方式对我们来说也不过是小菜一碟了。
本文的3、4、5 三节中使用的需求和布局是一模一样的,甚至4.2 和5.3 节的工程就是直接从3.1节中的工程拷贝过来的,唯一不同的就是使用提交数据的框架(类)不同。因此这里一次性将需求给出。

2.1 需求说明

如图1-1 所示,界面整体采用垂直的线性布局,前两行为两个EditText,分别代表用户名和密码。第三、四两行为两个Button,前者点击后采用get 方式提交数据,后者点击后采用post 方式提交数据。数据提交成功后,服务器会有返回值,并将返回值用Toast 显示出来。

2.2 服务器搭建

服务端采用Servlet 编写,名为LoginServlet,并使用Tomcat 作为其服务器。LoginServlet.java 源码见【文件1-1】,其中黄色高亮部分为核心代码。该Servlet 在web.xml 中的配置见【文件1-2】。因为服务器不是本文的重点,因此这里只简单介绍。

【文件1-1】LoginServlet.java

  1. package com.itheima.servlet;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class LoginServlet extends HttpServlet {
  8. /** * Constructor of the object. */
  9. public LoginServlet() {
  10. super();
  11. }
  12. /** * Destruction of the servlet. <br> */
  13. public void destroy() {
  14. super.destroy(); // Just puts "destroy" string in log
  15. // Put your code here
  16. }
  17. /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
  18. public void doGet(HttpServletRequest request, HttpServletResponse response)
  19. throws ServletException, IOException {
  20. request.setCharacterEncoding("utf-8");
  21. String username = request.getParameter("username");
  22. String password = request.getParameter("password");
  23. if ("GET".equals(request.getMethod().toUpperCase())) {
  24. byte[] bytes = username.getBytes("iso-8859-1");
  25. username = new String(bytes, "utf-8");
  26. }
  27. System.out.println("usernmae===="+username);
  28. System.out.println("password==="+password);
  29. response.setCharacterEncoding("utf-8");
  30. response.getWriter().write("成功收到信息"+username+"/"+password);
  31. }
  32. /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
  33. public void doPost(HttpServletRequest request, HttpServletResponse response)
  34. throws ServletException, IOException {
  35. doGet(request, response);
  36. }
  37. /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */
  38. public void init() throws ServletException {
  39. // Put your code here
  40. }
  41. }

【文件1-2】web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  3. <servlet>
  4. <servlet-name>LoginServlet</servlet-name>
  5. <servlet-class>com.itheima.servlet.LoginServlet</servlet-class>
  6. </servlet>
  7. <servlet>
  8. <servlet-name>FileuploadServlet</servlet-name>
  9. <servlet-class>com.itheima.servlet.FileuploadServlet</servlet-class>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>LoginServlet</servlet-name>
  13. <url-pattern>/servlet/LoginServlet</url-pattern>
  14. </servlet-mapping>
  15. <servlet-mapping>
  16. <servlet-name>FileuploadServlet</servlet-name>
  17. <url-pattern>/servlet/FileuploadServlet</url-pattern>
  18. </servlet-mapping>
  19. <welcome-file-list>
  20. <welcome-file>index.jsp</welcome-file>
  21. </welcome-file-list>
  22. </web-app>

SouthEast

2.3 编写布局

考虑到3、4、5节使用的工程布局是一模一样的,因此在这里先将布局给出。

【文件1-3】activity_main.java

  1. <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">
  2. <EditText android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名" />
  3. <EditText android:id="@+id/et_password" android:inputType="textPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" />
  4. <Button android:onClick="login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="right" android:text="get 方式登录" />
  5. <Button android:onClick="login2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="right" android:text="post 方式登录" />
  6. </LinearLayout>

2.4 添加权限

凡是网络访问的操作,必须添加如下权限。

  1. <uses-permission android:name="android.permission.INTERNET"/>

3. 使用HttpURLConnection 提交数据

3.1 代码

MainActivity.java 代码清单见【文件1-4】。
【文件1-4】MainActivity.java

  1. package com.itheima.userlogin;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.net.URLEncoder;
  7. import com.itheima.userlogin1.R;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.app.Activity;
  11. import android.text.TextUtils;
  12. import android.view.View;
  13. import android.widget.EditText;
  14. import android.widget.Toast;
  15. /** * 使用HttpURLConnection 提交数据 * 在该案例中分别使用了get 和post 两种 * 方式提交数据。 * 大家可以对比这两种方式使用上的不同。 */
  16. public class MainActivity extends Activity {
  17. protected static final int TIME_OUT = 5000;
  18. private EditText et_password;
  19. private EditText et_username;
  20. private Handler handler = new Handler() {
  21. @Override
  22. public void handleMessage(android.os.Message msg) {
  23. switch (msg.what) {
  24. case RESULT_OK:
  25. Toast.makeText(MainActivity.this, "成功:"
  26. + msg.obj.toString(), Toast.LENGTH_LONG).show();
  27. break;
  28. case RESULT_CANCELED:
  29. Toast.makeText(MainActivity.this, "失败:"
  30. + msg.obj.toString(), Toast.LENGTH_LONG).show();
  31. break;
  32. }
  33. }
  34. };
  35. @Override
  36. protected void onCreate(Bundle savedInstanceState) {
  37. super.onCreate(savedInstanceState);
  38. setContentView(R.layout.activity_main);
  39. //获取控件
  40. et_username = (EditText) findViewById(R.id.et_username);
  41. et_password = (EditText) findViewById(R.id.et_password);
  42. }
  43. public void login(View view) { // 使用get 方式完成用户的登录
  44. //获取用户数据
  45. final String username = et_username.getText().toString().trim();
  46. final String password = et_password.getText().toString().trim();
  47. //校验数据
  48. if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
  49. Toast.makeText(this, "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
  50. return;
  51. }
  52. //开启子线程
  53. new Thread(new Runnable() {
  54. @Override
  55. public void run() {
  56. // 因为是get 方式提交参数,因此对提交的参数必须使用URLEncoder.encode(String)方法进行编码,
  57. // 该编码可以将中文、空格、特殊字符等转义为16 进制的数字,这样可以兼容不同平台的差异性,
  58. // 而Tomcat 内部会自动将这些16 进制数给重新变为普通文本
  59. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet?username="
  60. + URLEncoder.encode(username) + "&password=" + password;
  61. try {
  62. URL url = new URL(path);
  63. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  64. //配置参数
  65. connection.setRequestMethod("GET");
  66. connection.setConnectTimeout(TIME_OUT);
  67. connection.setReadTimeout(TIME_OUT);
  68. //打开链接
  69. connection.connect();
  70. //获取状态码
  71. int responseCode = connection.getResponseCode();
  72. // 判断返回的状态码是否等于200,如果返回200 则代表请求成功
  73. if (200 == responseCode) {
  74. //获取返回值
  75. InputStream inputStream = connection.getInputStream();
  76. //将字节输入流转化为字符串
  77. String data = StreamUtils.inputStream2String(inputStream);
  78. //将数据通过handler 发送出去
  79. handler.obtainMessage(RESULT_OK, data).sendToTarget();
  80. } else {
  81. //如果返回状态码不等于200 则代码请求失败
  82. //将失败消息也发送出去
  83. handler.obtainMessage(RESULT_CANCELED, responseCode).sendToTarget();
  84. }
  85. } catch (Exception e) {
  86. e.printStackTrace();
  87. //将异常消息发送出去
  88. handler.obtainMessage(RESULT_CANCELED, e).sendToTarget();
  89. }
  90. }
  91. }).start();
  92. }
  93. public void login2(View view) { // 使用post 方式完成用户的登录
  94. //获取用户数据
  95. final String username = et_username.getText().toString().trim();
  96. final String password = et_password.getText().toString().trim();
  97. //校验数据
  98. if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
  99. Toast.makeText(this, "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
  100. return;
  101. }
  102. //开启子线程
  103. new Thread(new Runnable() {
  104. @Override
  105. public void run() {
  106. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet";
  107. try {
  108. URL url = new URL(path);
  109. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  110. //配置参数
  111. connection.setRequestMethod("POST");
  112. // 设置该参数,才能以流的形式提交数据,需要将要提交的数据转换为字节输出流
  113. connection.setDoOutput(true);
  114. connection.setConnectTimeout(TIME_OUT);
  115. connection.setReadTimeout(TIME_OUT);
  116. //将提交的参数进行URL 编码
  117. String param = "username=" + URLEncoder.encode(username) + "&password=" +
  118. password;
  119. // 设置请求属性,相当于封装http 的请求头参数,设置请求体的的长度
  120. connection.setRequestProperty("Content-Length", param.length() + "");
  121. //设置请求体的类型
  122. connection.setRequestProperty("Content-Type", "application / x - www - " +
  123. "form - urlencoded");
  124. connection.connect(); //打开链接
  125. //获取输出流
  126. OutputStream os = connection.getOutputStream();
  127. //通过输出流将要提交的数据提交出去
  128. os.write(param.getBytes());
  129. //关闭输出流
  130. os.close();
  131. //判断状态码
  132. int responseCode = connection.getResponseCode();
  133. if (200 == responseCode) {
  134. //获取返回值
  135. InputStream inputStream = connection.getInputStream();
  136. //将字节流转换为字符串
  137. String data = StreamUtils.inputStream2String(inputStream);
  138. handler.obtainMessage(RESULT_OK, data).sendToTarget();
  139. } else {
  140. handler.obtainMessage(RESULT_CANCELED, responseCode).sendToTarget();
  141. }
  142. } catch (Exception e) {
  143. e.printStackTrace();
  144. handler.obtainMessage(RESULT_CANCELED, e).sendToTarget();
  145. }
  146. }
  147. }).start();
  148. }
  149. }

3.2 总结

在http 协议中,get 请求协议没有请求体,只有请求头和请求行,因此如果想使用get 方式提交数据,只能通过在url 后面加上要提交的参数。这也意味着get 方式只能提交比较小的参数。

如果get 方式提交的参数有特殊字符或者中文字符那么必须对其进行URL 编码,不然会导致服务器接收到的数据乱码。

对于post 请求,提交的数据位于请求体中,因此需要设置connection.setDoOutput(true);参数,该参数设置后才允许将提交的数据通过输出流的形式提交。不过需要说明的是虽然采用post 方式提交,依然需要将参数进行URL 编码。

其实当我们使用浏览器进行form 表单提交的时候,浏览器内部已经帮我们实现了URL 编码。因为我们这里是使用代码模拟浏览器的提交数据过程,因此需要使用代码特殊处理。

4. 使用HttpClient 提交数据

HttpClient 是Apache Jakarta Common 下的子项目,提供了高效的、最新的、功能丰富的支持HTTP 协议的客户端编程工具包,并且它支持HTTP 协议最新的版本。
HttpClient 被内置到Android SDK 中,因此可以在不添加任何额外jar 包情况下,直接使用。(PS:Android 6.0 后HttpClient 已经被删除)

4.1 get 方式提交

在1.2 节工程的基础上,只需要修改部分代码即可。因此这里只给出核心代码。

【文件1-5】get 方式提交数据代码片段

  1. /**HttpCLient 使用get 方式完成用户的登录*/
  2. public void login3(View view) {
  3. // 获取用户数据
  4. final String username = et_username.getText().toString().trim();
  5. final String password = et_password.getText().toString().trim();
  6. // 校验数据
  7. if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
  8. Toast.makeText(this, "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
  9. return;
  10. }
  11. // 开启子线程
  12. new Thread(new Runnable() {
  13. @Override
  14. public void run() {
  15. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet?username="
  16. + URLEncoder.encode(username) + "&password=" + password;
  17. try {
  18. // 创建一个httpClient 对象
  19. HttpClient client = new DefaultHttpClient();
  20. // 创建一个请求方式
  21. HttpGet request = new HttpGet(path);
  22. // 执行操作
  23. HttpResponse response = client.execute(request);
  24. // 获取放回状态对象
  25. StatusLine statusLine = response.getStatusLine();
  26. // 获取状态码
  27. int statusCode = statusLine.getStatusCode();
  28. if (200 == statusCode) {
  29. // 获取服务器返回的对象
  30. HttpEntity entity = response.getEntity();
  31. // 获取输入流
  32. InputStream inputStream = entity.getContent();
  33. // 将输入流转化为字符串
  34. String data = StreamUtils.inputStream2String(inputStream);
  35. handler.obtainMessage(RESULT_OK, data).sendToTarget();
  36. } else {
  37. handler.obtainMessage(RESULT_CANCELED, statusCode).sendToTarget();
  38. }
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. handler.obtainMessage(RESULT_CANCELED, e).sendToTarget();
  42. }
  43. }
  44. }).start();
  45. }

4.2 post 方式提交

【文件1-6】post 方式提交数据代码片段

  1. /**HttpCLient 使用post 方式完成用户的登录*/
  2. public void login4(View view) {
  3. // 获取用户数据
  4. final String username = et_username.getText().toString().trim();
  5. final String password = et_password.getText().toString().trim();
  6. // 校验数据
  7. if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
  8. Toast.makeText(this, "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
  9. return;
  10. }
  11. // 开启子线程
  12. new Thread(new Runnable() {
  13. @Override
  14. public void run() {
  15. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet";
  16. try {
  17. // 创建一个httpClient 对象
  18. HttpClient client = new DefaultHttpClient();
  19. // 创建一个post 请求方式
  20. HttpPost request = new HttpPost(path);
  21. //创建集合用于添加请求的数据
  22. List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
  23. //将请求数据添加到集合中
  24. parameters.add(new BasicNameValuePair("username", username));
  25. parameters.add(new BasicNameValuePair("password", password));
  26. /* * 创建请求实体对象 * UrlEncodedFormEntity 是HttpEntity 的子类, * 该类专门用于封装字符串类型的参数 * 指定数据的编码格式 */
  27. HttpEntity requestEntity = new UrlEncodedFormEntity(parameters, "utf-8");
  28. //设置请求体
  29. request.setEntity(requestEntity);
  30. // 执行操作
  31. HttpResponse response = client.execute(request);
  32. // 获取放回状态对象
  33. StatusLine statusLine = response.getStatusLine();
  34. // 获取状态码
  35. int statusCode = statusLine.getStatusCode();
  36. if (200 == statusCode) {
  37. // 获取服务器返回的对象
  38. HttpEntity entity = response.getEntity();
  39. // 获取输入流
  40. InputStream inputStream = entity.getContent();
  41. // 将输入流转化为字符串
  42. String data = StreamUtils.inputStream2String(inputStream);
  43. handler.obtainMessage(RESULT_OK, data).sendToTarget();
  44. } else {
  45. handler.obtainMessage(RESULT_CANCELED, statusCode).sendToTarget();
  46. }
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. handler.obtainMessage(RESULT_CANCELED, e).sendToTarget();
  50. }
  51. }
  52. }).start();
  53. }

4.3 总结

4.3.1 get 请求方式步骤

1、创建一个httpClient 对象

  1. HttpClient client = new DefaultHttpClient();

2、创建一个请求方式

  1. String path ="http://10.0.2.2:8080/userlogin/servlet/LoginServlet?username="
  2. + URLEncoder.encode(username) + "&password=" + password;
  3. //因为是get 方式,因此需要在path 中添加请求参数
  4. HttpGet request = new HttpGet(path);

3、开始访问网络,并接收返回值

  1. HttpResponse response = client.execute(request);

4、获取返回状态码

  1. //获取返回值的状态行
  2. StatusLine statusLine = response.getStatusLine();
  3. // 获取状态码
  4. int statusCode = statusLine.getStatusCode();

5、判断状态码

  1. //如果状态码为200 则代表请求成功
  2. if (200 == statusCode) {
  3. //TODO}

6、获取返回数据

  1. // 获取服务器返回的对象
  2. HttpEntity entity = response.getEntity();
  3. // 获取输入流
  4. InputStream inputStream = entity.getContent();

4.3.2 post 请求方式步骤

1、创建一个httpClient 对象

  1. HttpClient client = new DefaultHttpClient();

2、创建一个post 请求方式

  1. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet";
  2. HttpPost request = new HttpPost(path);

3、设置请求体

  1. //创建集合用于添加请求的数据
  2. List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
  3. //将请求数据添加到集合中
  4. parameters.add(new BasicNameValuePair("username", username));
  5. parameters.add(new BasicNameValuePair("password", password));
  6. /* * 创建请求实体对象 * UrlEncodedFormEntity 是HttpEntity 的子类,该类专门用于封装字符串类型的参数 * 指定数据的编码格式 */
  7. HttpEntity requestEntity = new UrlEncodedFormEntity(parameters, "utf-8");
  8. //设置请求体
  9. request.setEntity(requestEntity);

4、开始访问网络,并接收返回值

  1. // 执行操作
  2. HttpResponse response = client.execute(request);

5、获取返回状态码

  1. //获取返回值的状态行
  2. StatusLine statusLine = response.getStatusLine();
  3. // 获取状态码
  4. int statusCode = statusLine.getStatusCode();

6、判断状态码

  1. //如果状态码为200 则代表请求成功
  2. if (200 == statusCode) {
  3. //TODO}

7、获取返回数据

  1. // 获取服务器返回的对象
  2. HttpEntity entity = response.getEntity();
  3. // 获取输入流
  4. InputStream inputStream = entity.getContent();

5. 使用AsyncHttpClient 框架提交数据

AsyncHttpClient 是开源免费的基于HttpClient 的网络请求框架,其源码托管在githu 上。下载地址
如图5-1 所示为AsyncHttpClient 在github 的网页,大家可以点击右下角的按钮,将源码下载下来,然后将下载好的压缩包解压,把src 目录中源码拷贝到自己的工程的src 目录下,比如图5-2所示。

SouthEast 1

SouthEast 2

5.1 get 方式提交

在1.2 节工程的基础上,只需要修改部分代码即可。因此这里只给出核心代码。
【文件1-7】get 方式提交数据代码片段

  1. /**使用AsyncHttpClient 的get 方式提交数据*/
  2. public void login5(View view) {
  3. // 获取用户数据
  4. final String username = et_username.getText().toString().trim();
  5. final String password = et_password.getText().toString().trim();
  6. // 校验数据
  7. if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
  8. Toast.makeText(this, "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
  9. return;
  10. }
  11. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet?username="
  12. + URLEncoder.encode(username) + "&password=" + password;
  13. // 创建一个AsyncHttpClient
  14. AsyncHttpClient client = new AsyncHttpClient();
  15. //执行get 方式请求
  16. client.get(path, new DataAsyncHttpResponseHandler() {
  17. /* * 请求网络是在子线程中进行的,当请求成功后回调onSuccess 方法, * 该方法是在主线程中被调用了,其内部是通过Handler 实现的 * 当请求成功后回调该方法 * 参数1:返回的状态码 * 参数2:响应头 * 参数3:返回的数据 */
  18. @Override
  19. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  20. Log.d("tag", Thread.currentThread().getName());
  21. //将responseBody 字节数组转化为字符串
  22. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  23. }
  24. // 当请求失败后回调该方法,该方法依然在主线程中被执行
  25. @Override
  26. public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
  27. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  28. }
  29. });
  30. }

5.2 post 方式提交

【文件1-8】post 方式提交数据代码片段

  1. /**使用AsyncHttpClient 的post 方式提交数据*/
  2. public void login6(View view) {
  3. // 获取用户数据
  4. final String username = et_username.getText().toString().trim();
  5. final String password = et_password.getText().toString().trim();
  6. // 校验数据
  7. if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
  8. Toast.makeText(this, "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
  9. return;
  10. }
  11. String path = "http://10.0.2.2:8080/userlogin/servlet/LoginServlet";
  12. // 创建一个AsyncHttpClient
  13. AsyncHttpClient client = new AsyncHttpClient();
  14. //封装请求参数
  15. RequestParams params = new RequestParams();
  16. params.put("username", username);
  17. params.put("password", password);
  18. /* * 执行post 请求 * 参数1:url 地址 * 参数2:请求参数 * 参数3:回调接口,在该接口中实现成功和失败方法,该过程是异步的。 */
  19. client.post(path, params, new DataAsyncHttpResponseHandler() {
  20. @Override
  21. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
  22. {
  23. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  24. }
  25. @Override
  26. public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
  27. Throwable error) {
  28. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  29. }
  30. });
  31. }

5.3 总结

5.3.1 get 请求方式步骤

1、创建一个AsyncHttpClient 对象

  1. AsyncHttpClient client = new AsyncHttpClient();

2、执行get 方法

  1. /* * 执行get 方式请求 * 参数1:请求的url 地址 * 参数2:回调接口。在该接口中实现相应成功和失败方法,该过程是异步的。 */
  2. client.get(path, new DataAsyncHttpResponseHandler() {
  3. /* * 请求网络是在子线程中进行的,当请求成功后回调onSuccess 方法, * 该方法是在主线程中被调用了,其内部是通过Handler 实现的 * 当请求成功后回调该方法 * 参数1:返回的状态码 * 参数2:响应头 * 参数3:返回的数据 */
  4. @Override
  5. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  6. Log.d("tag", Thread.currentThread().getName());
  7. //将responseBody 字节数组转化为字符串
  8. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  9. }
  10. // 当请求失败后回调该方法,该方法依然在主线程中被执行
  11. @Override
  12. public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
  13. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  14. }
  15. });

在执行get 方法的时候需要传递一个ResponseHandlerInterface 接口的子类, 在上面使用了DataAsyncHttpResponseHandler 抽象类,除此之外其实ResponseHandlerInterface 还有很多子类,比如用于接收json 字符串的TextHttpResponseHandler,用于接收文件下载的TextHttpResponseHandler。因为我们只需要接收字节数组,并将字节数组转化为字符串即可,因此我们使用DataAsyncHttpResponseHandler 抽象类。

5.3.2 post 方式请求步骤

1、创建一个AsyncHttpClient 对象

  1. AsyncHttpClient client = new AsyncHttpClient();

2、封装请求参数

  1. //封装请求参数
  2. RequestParams params = new RequestParams();
  3. params.put("username", username);
  4. params.put("password", password);

3、执行post 方法

  1. /* * 执行post 请求 * 参数1:url 地址 * 参数2:请求参数 * 参数3:回调接口,在该接口中实现成功和失败方法,该过程是异步的。 */
  2. client.post(path, params, new DataAsyncHttpResponseHandler() {
  3. @Override
  4. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  5. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  6. }
  7. @Override
  8. public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
  9. Throwable error) {
  10. Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
  11. }
  12. });

post 方法跟get 方式不同的就是多了一个RequestParams 参数。

6. JavaSE 实现多线程下载

6.1 多线程下载原理

多线程下载就是将同一个网络上的原始文件根据线程个数分成均等份,然后每个单独的线程下载对应的一部分,然后再将下载好的文件按照原始文件的顺序“拼接”起来就构成了完整的文件了。这样就大大提高了文件的下载效率。

多线程下载大致可分为以下几个步骤:

1)获取服务器上的目标文件的大小

显然这一步是需要先访问一下网络,只需要获取到目标文件的总大小即可。目的是为了计算每个线程应该分配的下载任务。

2)计算每个线程下载的起始位置和结束位置

我们可以把原始文件当成一个字节数组,每个线程只下载该“数组”的指定起始位置和指定结束位置之间的部分。在第一步中我们已经知道了“数组”的总长度。因此只要再知道总共开启的线程的个数就好
计算每个线程要下载的范围了。

每个线程需要下载的字节个数(blockSize)= 总字节数(totalSize)/线程数(threadCount)
假设给线程按照0,1,2,3…n 的方式依次进行编号,那么第n 个线程下载文件的范围为:
起始脚标 startIndex=n*blockSize
结束脚标 endIndex=(n-1)*blockSize-1
考虑到totalSize/threadCount 不一定能整除,因此对已最后一个线程应该特殊处理,最后一个线程的起始脚标计算公式不变,但是结束脚标endIndex=totalSize-1;即可。

3)在本地创建一个跟原始文件同样大小的文件
在本地可以通过RandomAccessFile 创建一个跟目标文件同样大小的文件,该api 支持文件任意位置的读写操作。这样就给多线程下载提供了方便,每个线程只需在指定起始和结束脚标范围内写数据即可。
4)开启多个子线程开始下载
5)记录下载进度
为每一个单独的线程创建一个临时文件,用于记录该线程下载的进度。对于单独的一个线程,每下载一部分数据就在本地文件中记录下当前下载的字节数。这样子如果下载任务异常终止了,那么下次重新开
始下载时就可以接着上次的进度下载。
6)删除临时文件
当多个线程都下载完成之后,最后一个下载完的线程将所有的临时文件删除。

6.2 代码实现

【文件1-9】多线程下载JavaSE 代码

  1. package com.itheima.se.download;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.FileWriter;
  7. import java.io.InputStream;
  8. import java.io.RandomAccessFile;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. public class MultiDownlodTest { // 实现多线程断点续下载
  12. public static void main(String[] args) {
  13. String sourcePath = "http://localhost:8080/FeiQ.exe";
  14. String targetPath = "d://FeiQ.exe";
  15. new MultiDownloader(sourcePath,3,targetPath).download();
  16. }
  17. static class MultiDownloader {
  18. private String sourcePath;
  19. private int threadCount;
  20. private String targetPath;
  21. //未完成任务的线程
  22. private int threadRunning;
  23. public MultiDownloader(String sourcePath,int threadCount,String targetPath){
  24. this.sourcePath = sourcePath;
  25. this.threadCount = threadCount;
  26. this.targetPath = targetPath;
  27. }
  28. public void download(){
  29. try {
  30. URL url = new URL(sourcePath);
  31. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  32. //配置连接参数
  33. connection.setRequestMethod("GET");
  34. connection.setConnectTimeout(5000);
  35. //打开连接
  36. connection.connect();
  37. int responseCode = connection.getResponseCode();
  38. if (responseCode==200) {
  39. int totalSize = connection.getContentLength();
  40. //计算每个线程下载的平均字节数
  41. int avgSize = totalSize/threadCount;
  42. for(int i=0;i<threadCount;i++){
  43. final int startIndex = i*avgSize;
  44. int endIndex = 0;
  45. if (i==threadCount-1) {
  46. endIndex = totalSize-1;
  47. }else {
  48. endIndex = (i+1)*avgSize-1;
  49. }
  50. threadRunning++;
  51. //开启子线程,实现下载
  52. new MyDownloadThread(i, startIndex, endIndex,targetPath,sourcePath).start();
  53. }
  54. }else {
  55. System.out.println("返回码为:"+responseCode+" 请求文件长度失败!");
  56. return;
  57. }
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. class MyDownloadThread extends Thread{
  63. private int id;
  64. private int startIndex;
  65. private int endIndex;
  66. private String targetPath;
  67. private String sourcePath;
  68. public MyDownloadThread(int id,int startIndex, int endIndex,String targetPath,String sourcePath){
  69. this.id = id;
  70. this.startIndex = startIndex;
  71. this.endIndex = endIndex;
  72. this.targetPath = targetPath;
  73. this.sourcePath = sourcePath;
  74. }
  75. @Override
  76. public void run() {
  77. try {
  78. URL url = new URL(sourcePath);
  79. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  80. //设置断点下载参数
  81. connection.setRequestMethod("GET");
  82. File file = new File("d://"+id+".tmp");
  83. // 该属性设置后,返回的状态码就不再是200,而是206
  84. int currentIndex = -1;
  85. //读进度
  86. if (file.exists()) {
  87. BufferedReader reader = new BufferedReader(new FileReader(file));
  88. String readLine = reader.readLine();
  89. currentIndex = Integer.valueOf(readLine);
  90. reader.close();
  91. }else {
  92. currentIndex = startIndex;
  93. }
  94. // 只有设置了该属性才能下载指定范围的文件
  95. connection.setRequestProperty("Range", "bytes="+currentIndex+"-"+endIndex);
  96. connection.setConnectTimeout(5000);
  97. connection.setReadTimeout(5000);
  98. connection.connect();
  99. int responseCode = connection.getResponseCode();
  100. //因为请求的是一个文件的部分,因此返回的状体码是206
  101. if (responseCode==206) {
  102. InputStream inputStream = connection.getInputStream();
  103. //支持随机读写的文件类
  104. RandomAccessFile raf = new RandomAccessFile(targetPath, "rws");
  105. //将文件指针定位到要写的位置
  106. raf.seek(currentIndex);
  107. byte[] buffer = new byte[1024*16];
  108. int len = -1;
  109. int totalDownloded = 0;
  110. while((len=inputStream.read(buffer))!=-1){
  111. raf.write(buffer, 0, len);
  112. totalDownloded+=len;
  113. //写进度
  114. BufferedWriter writer = new BufferedWriter(new FileWriter(file));
  115. writer.write(currentIndex+totalDownloded+"");
  116. writer.close();
  117. System.out.println(id+"下载了:"+totalDownloded+","+
  118. (totalDownloded+currentIndex-startIndex)*100/(endIndex-startIndex)+"%");
  119. }
  120. raf.close();
  121. inputStream.close();
  122. connection.disconnect();
  123. //线程执行完了
  124. threadRunning--;
  125. if (threadRunning==0) {
  126. for(int i=0;i<threadCount;i++){
  127. File tmpFile = new File("d://"+i+".tmp");
  128. tmpFile.delete();
  129. }
  130. }
  131. }else {
  132. System.out.println("返回的状态码为:"+responseCode+ " 下载失败!");
  133. }
  134. } catch (Exception e) {
  135. e.printStackTrace();
  136. }
  137. }
  138. }
  139. }
  140. }

6.3 新技能:

  • 多线程下载文件的请求属性

如果我们想请求服务器上某文件的一部分,而不是将整个文件都下载下来,那么就必须设置如下属性:

  1. connection.setRequestProperty("Range", "bytes="+currentIndex+"-"+endIndex);
  • 请求部分文件返回成功的状态码是206

当我们请求部分文件成功后,服务器返回的状态码不是200,而是206。

7. Android 实现多线程下载

将上面JavaSE 实现多线程下载的代码经过一定的改造,便可移植到Android 上。有所不同的是Android有界面可以跟用户进行良好的交互,在界面(如图1-4)上让用户输入原文件地址、线程个数,然后点击确定开始下载。为了让用户可以清晰的看到每个线程下载的进度根据线程个数动态的生成等量的进度条(ProgressBar)。

多线程下载

7.1 ProgressBar 的使用

ProgressBar 是一个进度条控件,用于显示一项任务的完成进度。其有两种样式,一种是圆形的,该种样式是系统默认的,由于无法显示具体的进度值,适合用于不确定要等待多久的情形下;另一种是长条形的, ,此类进度条有两种颜色,高亮颜色代表任务完成的总进度。对于我们下载任务来说,由于总任务(要下载的字节数)是明确的,当前已经完成的任务(已经下载的字节数)也是明确的,因此特别适合使用后者。

由于在我们的需求里ProgressBar 是需要根据线程的个数动态添加的,而且要求是长条形的。因此可以事先在布局文件中编写好ProgressBar 的样式。当需要用到的时候再将该布局(见【文件1-11】)填充起来。
ProgressBar 的max 属性代表其最大刻度值,progress 属性代表当前进度值。使用方法如下:

  1. ProgressBar.setMax(int max); // 设置最大刻度值。
  2. ProgressBar.setProgress(int progress); // 设置当前进度值。

给ProgressBar 设置最大刻度值和修改进度值可以在子线程中操作的,其内部已经特殊处理过了,因此不需要再通过发送Message 让主线程修改进度。

7.2 编写布局

这里给出两个布局,【文件1-10】是MainActivity 的布局,其显示效果如图1-4。【文件1-11】是ProgressBar布局。

【文件1-10】activity_main.java

  1. <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">
  2. <EditText android:id="@+id/et_url" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="http://10.0.2.2:8080/FeiQ.exe" />
  3. <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" >
  4. <EditText android:id="@+id/et_threadCount" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="3" />
  5. <Button android:onClick="download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" />
  6. </LinearLayout>
  7. <LinearLayout android:id="@+id/ll_pbs" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
  8. </LinearLayout>
  9. </LinearLayout>

【文件1-11】progress_bar.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ProgressBar xmlns:android="http://schemas.android.com/apk/res/android" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" >
  3. </ProgressBar>

7.3 编写代码

【文件1-12】MainActivity.java

  1. package com.itheima.android.downloader;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.FileWriter;
  7. import java.io.InputStream;
  8. import java.io.RandomAccessFile;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import android.os.Bundle;
  12. import android.support.v4.app.FragmentActivity;
  13. import android.text.TextUtils;
  14. import android.view.View;
  15. import android.widget.EditText;
  16. import android.widget.LinearLayout;
  17. import android.widget.ProgressBar;
  18. import android.widget.Toast;
  19. /**Android 实现多线程断点续传*/
  20. public class MainActivity extends FragmentActivity {
  21. private EditText et_url;
  22. private EditText et_threadCount;
  23. //用于添加ProgressBar 的容器
  24. private LinearLayout ll_pbs;
  25. @Override
  26. protected void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_main);
  29. //初始化控件
  30. et_url = (EditText) findViewById(R.id.et_url);
  31. et_threadCount = (EditText) findViewById(R.id.et_threadCount);
  32. ll_pbs = (LinearLayout) findViewById(R.id.ll_pbs);
  33. }
  34. /**点击Button 绑定的方法开始下载任务*/
  35. public void download(View view) {
  36. // 获取用户输入的初始值
  37. final String sourcePath = et_url.getText().toString().trim();
  38. final int threadCount = Integer.valueOf(et_threadCount.getText().toString().trim());
  39. // 校验数据
  40. if (TextUtils.isEmpty(sourcePath) || threadCount < 1) {
  41. Toast.makeText(this, "输入的内容不合法!", Toast.LENGTH_SHORT).show();
  42. return;
  43. }
  44. //存储到Android 本地的位置
  45. final String targetPath = "/mnt/sdcard/FeiQ.exe";
  46. //初始化进度条
  47. //填充一个ProgressBar
  48. for(int i=0;i<threadCount;i++){
  49. //将进度条布局填充为ProgressBar
  50. ProgressBar pb = (ProgressBar) View.inflate(MainActivity.this, R.layout.progress_bar, null);
  51. //将ProgressBar 添加到LinearLayout 中
  52. ll_pbs.addView(pb);
  53. }
  54. //开启子线程开始下载任务
  55. new Thread(new Runnable() {
  56. @Override
  57. public void run() {
  58. //开启多线程下载器
  59. new MultiDownloader(sourcePath,threadCount,targetPath).download();
  60. }
  61. }).start();
  62. }
  63. class MultiDownloader {
  64. //服务器原始文件地址
  65. private String sourcePath;
  66. //线程个数
  67. private int threadCount;
  68. //本地目标存储文件路径
  69. private String targetPath;
  70. //未完成任务的线程
  71. private int threadRunning;
  72. public MultiDownloader(String sourcePath,int threadCount,String targetPath){
  73. this.sourcePath = sourcePath;
  74. this.threadCount = threadCount;
  75. this.targetPath = targetPath;
  76. }
  77. public void download(){
  78. try {
  79. URL url = new URL(sourcePath);
  80. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  81. //配置连接参数
  82. connection.setRequestMethod("GET");
  83. connection.setConnectTimeout(5000);
  84. //打开连接
  85. connection.connect();
  86. int responseCode = connection.getResponseCode();
  87. if (responseCode==200) {
  88. //获取总字节数
  89. int totalSize = connection.getContentLength();
  90. //计算每个线程下载的平均字节数
  91. int avgSize = totalSize/threadCount;
  92. //计算每个线程下载的范围
  93. for(int i=0;i<threadCount;i++){
  94. final int startIndex = i*avgSize;
  95. int endIndex = 0;
  96. if (i==threadCount-1) {
  97. endIndex = totalSize-1;
  98. }else {
  99. endIndex = (i+1)*avgSize-1;
  100. }
  101. threadRunning++;
  102. //开启子线程,实现下载
  103. new MyDownloadThread(i, startIndex, endIndex,targetPath,sourcePath).start();
  104. }
  105. }else {
  106. System.out.println("返回码为:"+responseCode+" 请求文件长度失败!");
  107. return;
  108. }
  109. } catch (Exception e) {
  110. e.printStackTrace();
  111. }
  112. }
  113. /**下载线程*/
  114. class MyDownloadThread extends Thread{
  115. private int id;
  116. private int startIndex;
  117. private int endIndex;
  118. private String targetPath;
  119. private String sourcePath;
  120. public MyDownloadThread(int id,int startIndex,
  121. int endIndex,String targetPath,String sourcePath){
  122. this.id = id;
  123. this.startIndex = startIndex;
  124. this.endIndex = endIndex;
  125. this.targetPath = targetPath;
  126. this.sourcePath = sourcePath;
  127. }
  128. @Override
  129. public void run() {
  130. try {
  131. URL url = new URL(sourcePath);
  132. HttpURLConnection connection =
  133. (HttpURLConnection) url.openConnection();
  134. //设置断点下载参数
  135. connection.setRequestMethod("GET");
  136. //根据线程的id 创建临时文件,用于记录下载的进度
  137. File file = new File("/mnt/sdcard/"+id+".tmp");
  138. // 该属性设置后,返回的状态码就不再是200,而是206
  139. int currentIndex = -1;
  140. //读进度
  141. if (file.exists()) {
  142. BufferedReader reader = new BufferedReader(new FileReader(file));
  143. String readLine = reader.readLine();
  144. //读取历史进度
  145. currentIndex = Integer.valueOf(readLine);
  146. reader.close();
  147. }else {
  148. currentIndex = startIndex;
  149. }
  150. //设置多线程下载属性
  151. connection.setRequestProperty("Range", "bytes="+currentIndex+"-"+endIndex);
  152. connection.setConnectTimeout(5000);
  153. connection.setReadTimeout(5000);
  154. connection.connect();
  155. int responseCode = connection.getResponseCode();
  156. if (responseCode==206) {
  157. InputStream inputStream = connection.getInputStream();
  158. //支持随机读写的文件类
  159. RandomAccessFile raf = new RandomAccessFile(targetPath, "rws");
  160. //将文件指针定位到要写的位置
  161. raf.seek(currentIndex);
  162. byte[] buffer = new byte[1024*16];
  163. int len = -1;
  164. int totalDownloded = 0;
  165. //获取线性布局的子控件(ProgressBar)
  166. ProgressBar pb = (ProgressBar) ll_pbs.getChildAt(id);
  167. //设置对打的进度值
  168. pb.setMax(endIndex-startIndex);
  169. while((len=inputStream.read(buffer))!=-1){
  170. raf.write(buffer, 0, len);
  171. totalDownloded+=len;
  172. //写进度
  173. BufferedWriter writer = new BufferedWriter(new FileWriter(file));
  174. writer.write(currentIndex+totalDownloded+"");
  175. writer.close();
  176. //修改进度条
  177. pb.setProgress(currentIndex+totalDownloded-startIndex);
  178. System.out.println(id+"下载了:"+totalDownloded+","+
  179. (totalDownloded+currentIndex-startIndex)*100/(endIndex-startIndex)+"%");
  180. }
  181. raf.close();
  182. inputStream.close();
  183. connection.disconnect();
  184. //线程执行完了
  185. threadRunning--;
  186. //如果所有的线程都下载完了,则删除所有的临时文件
  187. if (threadRunning==0) {
  188. for(int i=0;i<threadCount;i++){
  189. File tmpFile = new File("/mnt/sdcard/"+i+".tmp");
  190. tmpFile.delete();
  191. }
  192. }
  193. }else {
  194. System.out.println("返回的状态码为:"+responseCode+ " 下载失败!");
  195. }
  196. } catch (Exception e) {
  197. e.printStackTrace();
  198. }
  199. }
  200. }
  201. }
  202. }

添加权限,在该工程中不仅用到了网络访问还用到了sdcard 存储,因此需要添加两个权限。

  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

8. xUtils 实现多线程下载

8.1 xUtils 简介

xUtils 是开源免费的Android 工具包,代码托管在github 上。目前xUtils 主要有四大模块:

  • DbUtils 模块:操作数据库的框架。
  • ViewUtils 模块:通过注解的方式可以对UI,资源和事件绑定进行管理。
  • HttpUtils 模块:提供了方便的网络访问,断点续传等功能。
  • BitmapUtils 模块:提供了强大的图片处理工具。

我们在这里只简单实用xUtils 工具中的HttpUtils 工具。xUtils 的下载地址

xutils

8.2 xUtils 之HttpUtils 的使用

  • 下载xUtils 工具如图1-5 所示,右下角“Download ZIP”
  • 将下载好的zip 包解压,然后将src 下的源代码拷贝在自己工程中如图8-6

xutils

8.3 使用HttpUtils

HttpUtils 的使用非常简单,因此这里直接给出核心代码。【文件1-13】使用HttpUtils 完成文件下载

  1. /**使用xUtils 中的HttpUtils 模块进行下载*/
  2. public void downloadHttpUtils(View view){
  3. HttpUtils httpUtils = new HttpUtils();
  4. String url="http://10.0.2.2:8080/FeiQ.exe";
  5. String target = "/mnt/sdcard/FeiQ2.exe";
  6. /* * 参数1:原文件网络地址 * 参数2:本地保存的地址 * 参数3:是否支持断点续传,true:支持,false:不支持 * 参数4:回调接口,该接口中的方法都是在主线程中被调用的, * 也就是该接口中的方法都可以修改UI */
  7. httpUtils.download(url, target, true, new RequestCallBack<File>() {
  8. //当下载任务开始时被调用
  9. @Override
  10. public void onStart() {
  11. Log.d("tag", "onStart"+Thread.currentThread().getName());
  12. }
  13. /* * 每下载一部分就被调用一次,通过该方法可以知道当前下载进度 * 参数1:原文件总字节数 * 参数2:当前已经下载好的字节数 * 参数3:是否在上传,对于下载,该值为false */
  14. @Override
  15. public void onLoading(long total, long current, boolean isUploading) {
  16. Log.d("tag", "onLoading"+Thread.currentThread().getName()+"//"+
  17. "current"+current+"//"+"total="+total);
  18. }
  19. //下载成功后调用一次
  20. @Override
  21. public void onSuccess(ResponseInfo<File> responseInfo) {
  22. Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
  23. }
  24. //失败后调用一次
  25. @Override
  26. public void onFailure(HttpException error, String msg) {
  27. Toast.makeText(MainActivity.this, "下载失败:"+msg, Toast.LENGTH_LONG).show();
  28. }
  29. });
  30. }

1. HttpClient

1.1 发送get请求

  • 创建一个客户端对象

    HttpClient client = new DefaultHttpClient();

  • 创建一个get请求对象

    HttpGet hg = new HttpGet(path);

  • 发送get请求,建立连接,返回响应头对象

    HttpResponse hr = hc.execute(hg);

  • 获取状态行对象,获取状态码,如果为200则说明请求成功

    if(hr.getStatusLine().getStatusCode() == 200){

    1. //拿到服务器返回的输入流
    2. InputStream is = hr.getEntity().getContent();
    3. String text = Utils.getTextFromStream(is);

    }

1.2 发送post请求

  1. //创建一个客户端对象
  2. HttpClient client = new DefaultHttpClient();
  3. //创建一个post请求对象
  4. HttpPost hp = new HttpPost(path);
  • 往post对象里放入要提交给服务器的数据

    //要提交的数据以键值对的形式存在BasicNameValuePair对象中
    List parameters = new ArrayList();
    BasicNameValuePair bnvp = new BasicNameValuePair(“name”, name);
    BasicNameValuePair bnvp2 = new BasicNameValuePair(“pass”, pass);
    parameters.add(bnvp);
    parameters.add(bnvp2);
    //创建实体对象,指定进行URL编码的码表
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, “utf-8”);
    //为post请求设置实体
    hp.setEntity(entity);

1.3 案例1:HttpClient框架提交数据

  1. public class MainActivity extends Activity {
  2. Handler handler = new Handler(){
  3. @Override
  4. public void handleMessage(android.os.Message msg) {
  5. Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
  6. }
  7. };
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.activity_main);
  12. }
  13. public void get(View v){
  14. EditText et_name = (EditText) findViewById(R.id.et_name);
  15. EditText et_pass = (EditText) findViewById(R.id.et_pass);
  16. final String name = et_name.getText().toString();
  17. final String pass = et_pass.getText().toString();
  18. Thread t = new Thread(){
  19. @Override
  20. public void run() {
  21. String path = "http://192.168.13.13/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
  22. //使用httpClient框架做get方式提交
  23. //1.创建HttpClient对象
  24. HttpClient hc = new DefaultHttpClient();
  25. //2.创建httpGet对象,构造方法的参数就是网址
  26. HttpGet hg = new HttpGet(path);
  27. //3.使用客户端对象,把get请求对象发送出去
  28. try {
  29. HttpResponse hr = hc.execute(hg);
  30. //拿到响应头中的状态行
  31. StatusLine sl = hr.getStatusLine();
  32. if(sl.getStatusCode() == 200){
  33. //拿到响应头的实体
  34. HttpEntity he = hr.getEntity();
  35. //拿到实体中的内容,其实就是服务器返回的输入流
  36. InputStream is = he.getContent();
  37. String text = Utils.getTextFromStream(is);
  38. //发送消息,让主线程刷新ui显示text
  39. Message msg = handler.obtainMessage();
  40. msg.obj = text;
  41. handler.sendMessage(msg);
  42. }
  43. } catch (Exception e) {
  44. // TODO Auto-generated catch block
  45. e.printStackTrace();
  46. }
  47. }
  48. };
  49. t.start();
  50. }
  51. public void post(View v){
  52. EditText et_name = (EditText) findViewById(R.id.et_name);
  53. EditText et_pass = (EditText) findViewById(R.id.et_pass);
  54. final String name = et_name.getText().toString();
  55. final String pass = et_pass.getText().toString();
  56. Thread t = new Thread(){
  57. @Override
  58. public void run() {
  59. String path = "http://192.168.13.13/Web/servlet/CheckLogin";
  60. //1.创建客户端对象
  61. HttpClient hc = new DefaultHttpClient();
  62. //2.创建post请求对象
  63. HttpPost hp = new HttpPost(path);
  64. //封装form表单提交的数据
  65. BasicNameValuePair bnvp = new BasicNameValuePair("name", name);
  66. BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);
  67. List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
  68. //把BasicNameValuePair放入集合中
  69. parameters.add(bnvp);
  70. parameters.add(bnvp2);
  71. try {
  72. //要提交的数据都已经在集合中了,把集合传给实体对象
  73. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
  74. //设置post请求对象的实体,其实就是把要提交的数据封装至post请求的输出流中
  75. hp.setEntity(entity);
  76. //3.使用客户端发送post请求
  77. HttpResponse hr = hc.execute(hp);
  78. if(hr.getStatusLine().getStatusCode() == 200){
  79. InputStream is = hr.getEntity().getContent();
  80. String text = Utils.getTextFromStream(is);
  81. //发送消息,让主线程刷新ui显示text
  82. Message msg = handler.obtainMessage();
  83. msg.obj = text;
  84. handler.sendMessage(msg);
  85. }
  86. } catch (Exception e) {
  87. // TODO Auto-generated catch block
  88. e.printStackTrace();
  89. }
  90. }
  91. };
  92. t.start();
  93. }
  94. }
  95. if (code == 200) {
  96. // 数据获取成功
  97. // 获取读取的字节流
  98. InputStream is = conn.getInputStream();
  99. // 把字节流转换成字符流
  100. bfr = new BufferedReader(new InputStreamReader(is));
  101. // 读取一行信息
  102. String line = bfr.readLine();
  103. // json字符串数据的封装
  104. StringBuilder json = new StringBuilder();
  105. while (line != null) {
  106. json.append(line);
  107. line = bfr.readLine();
  108. }
  109. parseJson = parseJson(json);//返回数据封装信息
  110. }
  111. public class Utils {
  112. public static String getTextFromStream(InputStream is){
  113. byte[] b = new byte[1024];
  114. int len = 0;
  115. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  116. try {
  117. while((len = is.read(b)) != -1){
  118. bos.write(b, 0, len);
  119. }
  120. String text = new String(bos.toByteArray());
  121. bos.close();
  122. return text;
  123. } catch (IOException e) {
  124. // TODO Auto-generated catch block
  125. e.printStackTrace();
  126. }
  127. return null;
  128. }
  129. }

StreamUtils.java

  1. public class StreamUtils {
  2. /** * 将输入流读取成String后返回 * * @param in * @return * @throws IOException */
  3. public static String readFromStream(InputStream in) throws IOException {
  4. ByteArrayOutputStream out = new ByteArrayOutputStream();
  5. int len = 0;
  6. byte[] buffer = new byte[1024];
  7. while ((len = in.read(buffer)) != -1) {
  8. out.write(buffer, 0, len);
  9. }
  10. String result = out.toString();
  11. in.close();
  12. out.close();
  13. return result;
  14. }
  15. }

2. 异步HttpClient框架

2.1 发送get请求

  1. //创建异步的httpclient对象
  2. AsyncHttpClient ahc = new AsyncHttpClient();
  3. //发送get请求
  4. ahc.get(path, new MyHandler());
  • 注意AsyncHttpResponseHandler两个方法的调用时机

    class MyHandler extends AsyncHttpResponseHandler{

    1. //http请求成功,返回码为200,系统回调此方法
    2. @Override
    3. public void onSuccess(int statusCode, Header[] headers,
    4. //responseBody的内容就是服务器返回的数据
    5. byte[] responseBody) {
    6. Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
    7. }
    8. //http请求失败,返回码不为200,系统回调此方法
    9. @Override
    10. public void onFailure(int statusCode, Header[] headers,
    11. byte[] responseBody, Throwable error) {
    12. Toast.makeText(MainActivity.this, "返回码不为200", 0).show();
    13. }

    }

2.2 发送post请求

  • 使用RequestParams对象封装要携带的数据

    //创建异步httpclient对象
    AsyncHttpClient ahc = new AsyncHttpClient();
    //创建RequestParams封装要携带的数据
    RequestParams rp = new RequestParams();
    rp.add(“name”, name);
    rp.add(“pass”, pass);
    //发送post请求
    ahc.post(path, rp, new MyHandler());

2.3 案例2:异步HttpClient框架

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. }
  7. public void get(View v){
  8. EditText et_name = (EditText) findViewById(R.id.et_name);
  9. EditText et_pass = (EditText) findViewById(R.id.et_pass);
  10. final String name = et_name.getText().toString();
  11. final String pass = et_pass.getText().toString();
  12. String url = "http://192.168.13.13/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
  13. //创建异步httpclient
  14. AsyncHttpClient ahc = new AsyncHttpClient();
  15. //发送get请求提交数据
  16. ahc.get(url, new MyResponseHandler());
  17. }
  18. public void post(View v){
  19. EditText et_name = (EditText) findViewById(R.id.et_name);
  20. EditText et_pass = (EditText) findViewById(R.id.et_pass);
  21. final String name = et_name.getText().toString();
  22. final String pass = et_pass.getText().toString();
  23. String url = "http://192.168.13.13/Web/servlet/CheckLogin";
  24. //创建异步httpclient
  25. AsyncHttpClient ahc = new AsyncHttpClient();
  26. //发送post请求提交数据
  27. //把要提交的数据封装至RequestParams对象
  28. RequestParams params = new RequestParams();
  29. params.add("name", name);
  30. params.add("pass", pass);
  31. ahc.post(url, params, new MyResponseHandler());
  32. }
  33. class MyResponseHandler extends AsyncHttpResponseHandler{
  34. //请求服务器成功时,此方法调用
  35. @Override
  36. public void onSuccess(int statusCode, Header[] headers,
  37. byte[] responseBody) {
  38. Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
  39. }
  40. //请求失败此方法调用
  41. @Override
  42. public void onFailure(int statusCode, Header[] headers,
  43. byte[] responseBody, Throwable error) {
  44. Toast.makeText(MainActivity.this, "请求失败", 0).show();
  45. }
  46. }
  47. }

3. 多线程下载

原理:服务器CPU分配给每条线程的时间片相同,服务器带宽平均分配给每条线程,所以客户端开启的线程越多,就能抢占到更多的服务器资源

多线程下载

多线程下载

3.1 确定每条线程下载多少数据

  • 发送http请求至下载地址

    String path = “http://192.168.1.102:8080/editplus.exe“;
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(5000);
    conn.setConnectTimeout(5000);
    conn.setRequestMethod(“GET”);

  • 获取文件总长度,然后创建长度一致的临时文件

    if(conn.getResponseCode() == 200){
    //获得服务器流中数据的长度
    int length = conn.getContentLength();
    //创建一个临时文件存储下载的数据
    RandomAccessFile raf = new RandomAccessFile(getFileName(path), “rwd”);
    //设置临时文件的大小
    raf.setLength(length);
    raf.close();

  • 确定线程下载多少数据

    //计算每个线程下载多少数据
    int blockSize = length / THREAD_COUNT;

3.2 计算每条线程下载数据的开始位置和结束位置

  1. for(int id = 1; id <= 3; id++){
  2. //计算每个线程下载数据的开始位置和结束位置
  3. int startIndex = (id - 1) * blockSize;
  4. int endIndex = id * blockSize - 1;
  5. if(id == THREAD_COUNT){
  6. endIndex = length;
  7. }
  8. //开启线程,按照计算出来的开始结束位置开始下载数据
  9. new DownLoadThread(startIndex, endIndex, id).start();
  10. }

3.3 再次发送请求至下载地址,请求开始位置至结束位置的数据

  1. String path = "http://192.168.1.102:8080/editplus.exe";
  2. URL url = new URL(path);
  3. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  4. conn.setReadTimeout(5000);
  5. conn.setConnectTimeout(5000);
  6. conn.setRequestMethod("GET");
  7. //向服务器请求部分数据
  8. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  9. conn.connect();
  • 下载请求到的数据,存放至临时文件中

    if(conn.getResponseCode() == 206){

    1. InputStream is = conn.getInputStream();
    2. RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rwd");
    3. //指定从哪个位置开始存放数据
    4. raf.seek(startIndex);
    5. byte[] b = new byte[1024];
    6. int len;
    7. while((len = is.read(b)) != -1){
    8. raf.write(b, 0, len);
    9. }
    10. raf.close();

    }

3.4 案例3:多线程下载

  1. public class MultiDownload {
  2. static int ThreadCount = 3;
  3. static int finishedThread = 0;
  4. //确定下载地址
  5. static String path = "http://192.168.13.13:8080/QQPlayer.exe";
  6. public static void main(String[] args) {
  7. //发送get请求,请求这个地址的资源
  8. try {
  9. URL url = new URL(path);
  10. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  11. conn.setRequestMethod("GET");
  12. conn.setConnectTimeout(5000);
  13. conn.setReadTimeout(5000);
  14. if(conn.getResponseCode() == 200){
  15. //拿到所请求资源文件的长度
  16. int length = conn.getContentLength();
  17. File file = new File("QQPlayer.exe");
  18. //生成临时文件
  19. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  20. //设置临时文件的大小
  21. raf.setLength(length);
  22. raf.close();
  23. //计算出每个线程应该下载多少字节
  24. int size = length / ThreadCount;
  25. for (int i = 0; i < ThreadCount; i++) {
  26. //计算线程下载的开始位置和结束位置
  27. int startIndex = i * size;
  28. int endIndex = (i + 1) * size - 1;
  29. //如果是最后一个线程,那么结束位置写死
  30. if(i == ThreadCount - 1){
  31. endIndex = length - 1;
  32. }
  33. // System.out.println("线程" + i + "的下载区间是:" + startIndex + "---" + endIndex);
  34. new DownLoadThread(startIndex, endIndex, i).start();
  35. }
  36. }
  37. } catch (Exception e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. class DownLoadThread extends Thread{
  44. int startIndex;
  45. int endIndex;
  46. int threadId;
  47. public DownLoadThread(int startIndex, int endIndex, int threadId) {
  48. super();
  49. this.startIndex = startIndex;
  50. this.endIndex = endIndex;
  51. this.threadId = threadId;
  52. }
  53. @Override
  54. public void run() {
  55. //再次发送http请求,下载原文件
  56. try {
  57. File progressFile = new File(threadId + ".txt");
  58. //判断进度临时文件是否存在
  59. if(progressFile.exists()){
  60. FileInputStream fis = new FileInputStream(progressFile);
  61. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  62. //从进度临时文件中读取出上一次下载的总进度,然后与原本的开始位置相加,得到新的开始位置
  63. startIndex += Integer.parseInt(br.readLine());
  64. fis.close();
  65. }
  66. System.out.println("线程" + threadId + "的下载区间是:" + startIndex + "---" + endIndex);
  67. HttpURLConnection conn;
  68. URL url = new URL(MultiDownload.path);
  69. conn = (HttpURLConnection) url.openConnection();
  70. conn.setRequestMethod("GET");
  71. conn.setConnectTimeout(5000);
  72. conn.setReadTimeout(5000);
  73. //设置本次http请求所请求的数据的区间
  74. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  75. //请求部分数据,相应码是206
  76. if(conn.getResponseCode() == 206){
  77. //流里此时只有1/3原文件的数据
  78. InputStream is = conn.getInputStream();
  79. byte[] b = new byte[1024];
  80. int len = 0;
  81. int total = 0;
  82. //拿到临时文件的输出流
  83. File file = new File("QQPlayer.exe");
  84. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  85. //把文件的写入位置移动至startIndex
  86. raf.seek(startIndex);
  87. while((len = is.read(b)) != -1){
  88. //每次读取流里数据之后,同步把数据写入临时文件
  89. raf.write(b, 0, len);
  90. total += len;
  91. // System.out.println("线程" + threadId + "下载了" + total);
  92. //生成一个专门用来记录下载进度的临时文件
  93. RandomAccessFile progressRaf = new RandomAccessFile(progressFile, "rwd");
  94. //每次读取流里数据之后,同步把当前线程下载的总进度写入进度临时文件中
  95. progressRaf.write((total + "").getBytes());
  96. progressRaf.close();
  97. }
  98. System.out.println("线程" + threadId + "下载完毕-------------------小志参上!");
  99. raf.close();
  100. MultiDownload.finishedThread++;
  101. synchronized (MultiDownload.path) {
  102. if(MultiDownload.finishedThread == MultiDownload.ThreadCount){
  103. for (int i = 0; i < MultiDownload.ThreadCount; i++) {
  104. File f = new File(i + ".txt");
  105. f.delete();
  106. }
  107. MultiDownload.finishedThread = 0;
  108. }
  109. }
  110. }
  111. } catch (Exception e) {
  112. // TODO Auto-generated catch block
  113. e.printStackTrace();
  114. }
  115. }
  116. }

4. 带断点续传的多线程下载

  • 定义一个int变量记录每条线程下载的数据总长度,然后加上该线程的下载开始位置,得到的结果就是下次下载时,该线程的开始位置,把得到的结果存入缓存文件

    //用来记录当前线程总的下载长度
    int total = 0;
    while((len = is.read(b)) != -1){

    1. raf.write(b, 0, len);
    2. total += len;
    3. //每次下载都把新的下载位置写入缓存文本文件
    4. RandomAccessFile raf2 = new RandomAccessFile(threadId + ".txt", "rwd");
    5. raf2.write((startIndex + total + "").getBytes());
    6. raf2.close();

    }

  • 下次下载开始时,先读取缓存文件中的值,得到的值就是该线程新的开始位置

    FileInputStream fis = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String text = br.readLine();
    int newStartIndex = Integer.parseInt(text);
    //把读到的值作为新的开始位置
    startIndex = newStartIndex;
    fis.close();

  • 三条线程都下载完毕之后,删除缓存文件

    RUNNING_THREAD—;
    if(RUNNING_THREAD == 0){

    1. for(int i = 0; i <= 3; i++){
    2. File f = new File(i + ".txt");
    3. f.delete();
    4. }

    }

5. 手机版的断点续传多线程下载器

  • 把刚才的代码直接粘贴过来就能用,记得在访问文件时的路径要改成Android的目录,添加访问网络和外部存储的路径

5.1 用进度条显示下载进度

  • 拿到下载文件总长度时,设置进度条的最大值

    pb.setMax(length);//设置进度条的最大值

  • 进度条需要显示三条线程的整体下载进度,所以三条线程每下载一次,就要把新下载的长度加入进度条

  1. * 定义一个int全局变量,记录三条线程的总下载长度
  2. int progress;
  • 刷新进度条

    while((len = is.read(b)) != -1){
    raf.write(b, 0, len);

    //把当前线程本次下载的长度加到进度条里
    progress += len;
    pb.setProgress(progress);

  • 每次断点下载时,从新的开始位置开始下载,进度条也要从新的位置开始显示,在读取缓存文件获取新的下载开始位置时,也要处理进度条进度

    FileInputStream fis = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String text = br.readLine();
    int newStartIndex = Integer.parseInt(text);

    //新开始位置减去原本的开始位置,得到已经下载的数据长度
    int alreadyDownload = newStartIndex - startIndex;
    //把已经下载的长度设置入进度条
    progress += alreadyDownload;

5.2 添加文本框显示百分比进度

  1. tv.setText(progress * 100 / pb.getMax() + "%");

5.3 案例4:断点续传

  1. public class MainActivity extends Activity {
  2. static int ThreadCount = 3;
  3. static int finishedThread = 0;
  4. int currentProgress;
  5. String fileName = "QQPlayer.exe";
  6. //确定下载地址
  7. String path = "http://192.168.13.13:8080/" + fileName;
  8. private ProgressBar pb;
  9. TextView tv;
  10. Handler handler = new Handler(){
  11. public void handleMessage(android.os.Message msg) {
  12. //把变量改成long,在long下运算
  13. tv.setText((long)pb.getProgress() * 100 / pb.getMax() + "%");
  14. }
  15. };
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. pb = (ProgressBar) findViewById(R.id.pb);
  21. tv = (TextView) findViewById(R.id.tv);
  22. }
  23. public void click(View v){
  24. Thread t = new Thread(){
  25. @Override
  26. public void run() {
  27. //发送get请求,请求这个地址的资源
  28. try {
  29. URL url = new URL(path);
  30. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  31. conn.setRequestMethod("GET");
  32. conn.setConnectTimeout(5000);
  33. conn.setReadTimeout(5000);
  34. if(conn.getResponseCode() == 200){
  35. //拿到所请求资源文件的长度
  36. int length = conn.getContentLength();
  37. //设置进度条的最大值就是原文件的总长度
  38. pb.setMax(length);
  39. File file = new File(Environment.getExternalStorageDirectory(), fileName);
  40. //生成临时文件
  41. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  42. //设置临时文件的大小
  43. raf.setLength(length);
  44. raf.close();
  45. //计算出每个线程应该下载多少字节
  46. int size = length / ThreadCount;
  47. for (int i = 0; i < ThreadCount; i++) {
  48. //计算线程下载的开始位置和结束位置
  49. int startIndex = i * size;
  50. int endIndex = (i + 1) * size - 1;
  51. //如果是最后一个线程,那么结束位置写死
  52. if(i == ThreadCount - 1){
  53. endIndex = length - 1;
  54. }
  55. // System.out.println("线程" + i + "的下载区间是:" + startIndex + "---" + endIndex);
  56. new DownLoadThread(startIndex, endIndex, i).start();
  57. }
  58. }
  59. } catch (Exception e) {
  60. // TODO Auto-generated catch block
  61. e.printStackTrace();
  62. }
  63. }
  64. };
  65. t.start();
  66. }
  67. class DownLoadThread extends Thread{
  68. int startIndex;
  69. int endIndex;
  70. int threadId;
  71. public DownLoadThread(int startIndex, int endIndex, int threadId) {
  72. super();
  73. this.startIndex = startIndex;
  74. this.endIndex = endIndex;
  75. this.threadId = threadId;
  76. }
  77. @Override
  78. public void run() {
  79. //再次发送http请求,下载原文件
  80. try {
  81. File progressFile = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
  82. //判断进度临时文件是否存在
  83. if(progressFile.exists()){
  84. FileInputStream fis = new FileInputStream(progressFile);
  85. BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  86. //从进度临时文件中读取出上一次下载的总进度,然后与原本的开始位置相加,得到新的开始位置
  87. int lastProgress = Integer.parseInt(br.readLine());
  88. startIndex += lastProgress;
  89. //把上次下载的进度显示至进度条
  90. currentProgress += lastProgress;
  91. pb.setProgress(currentProgress);
  92. //发送消息,让主线程刷新文本进度
  93. handler.sendEmptyMessage(1);
  94. fis.close();
  95. }
  96. System.out.println("线程" + threadId + "的下载区间是:" + startIndex + "---" + endIndex);
  97. HttpURLConnection conn;
  98. URL url = new URL(path);
  99. conn = (HttpURLConnection) url.openConnection();
  100. conn.setRequestMethod("GET");
  101. conn.setConnectTimeout(5000);
  102. conn.setReadTimeout(5000);
  103. //设置本次http请求所请求的数据的区间
  104. conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
  105. //请求部分数据,相应码是206
  106. if(conn.getResponseCode() == 206){
  107. //流里此时只有1/3原文件的数据
  108. InputStream is = conn.getInputStream();
  109. byte[] b = new byte[1024];
  110. int len = 0;
  111. int total = 0;
  112. //拿到临时文件的输出流
  113. File file = new File(Environment.getExternalStorageDirectory(), fileName);
  114. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  115. //把文件的写入位置移动至startIndex
  116. raf.seek(startIndex);
  117. while((len = is.read(b)) != -1){
  118. //每次读取流里数据之后,同步把数据写入临时文件
  119. raf.write(b, 0, len);
  120. total += len;
  121. System.out.println("线程" + threadId + "下载了" + total);
  122. //每次读取流里数据之后,把本次读取的数据的长度显示至进度条
  123. currentProgress += len;
  124. pb.setProgress(currentProgress);
  125. //发送消息,让主线程刷新文本进度
  126. handler.sendEmptyMessage(1);
  127. //生成一个专门用来记录下载进度的临时文件
  128. RandomAccessFile progressRaf = new RandomAccessFile(progressFile, "rwd");
  129. //每次读取流里数据之后,同步把当前线程下载的总进度写入进度临时文件中
  130. progressRaf.write((total + "").getBytes());
  131. progressRaf.close();
  132. }
  133. System.out.println("线程" + threadId + "下载完毕-------------------小志参上!");
  134. raf.close();
  135. finishedThread++;
  136. synchronized (path) {
  137. if(finishedThread == ThreadCount){
  138. for (int i = 0; i < ThreadCount; i++) {
  139. File f = new File(Environment.getExternalStorageDirectory(), i + ".txt");
  140. f.delete();
  141. }
  142. finishedThread = 0;
  143. }
  144. }
  145. }
  146. } catch (Exception e) {
  147. // TODO Auto-generated catch block
  148. e.printStackTrace();
  149. }
  150. }
  151. }
  152. }

6. HttpUtils的使用

HttpUtils本身就支持多线程断点续传,使用起来非常的方便

  • 创建HttpUtils对象

    HttpUtils http = new HttpUtils();

  • 下载文件

    http.download(

    1. url, //下载请求的网址
    2. target, //下载的数据保存路径和文件名
    3. true, //是否开启断点续传
    4. true, //如果服务器响应头中包含了文件名,那么下载完毕后自动重命名
    5. new RequestCallBack<File>() {

    //侦听下载状态

    1. //下载成功此方法调用
    2. @Override
    3. public void onSuccess(ResponseInfo<File> arg0) {
    4. tv.setText("下载成功" + arg0.result.getPath());
    5. }
    6. //下载失败此方法调用,比如文件已经下载、没有网络权限、文件访问不到,方法传入一个字符串参数告知失败原因
    7. @Override
    8. public void onFailure(HttpException arg0, String arg1) {
    9. tv.setText("下载失败" + arg1);
    10. }
    11. //在下载过程中不断的调用,用于刷新进度条
    12. @Override
    13. public void onLoading(long total, long current, boolean isUploading) {
    14. super.onLoading(total, current, isUploading);
    15. //设置进度条总长度
    16. pb.setMax((int) total);
    17. //设置进度条当前进度
    18. pb.setProgress((int) current);
    19. tv_progress.setText(current * 100 / total + "%");
    20. }

    });

6.1 案例5:开源框架xUtils的使用

  1. public class MainActivity extends Activity {
  2. private TextView tv_failure;
  3. private TextView tv_progress;
  4. private ProgressBar pb;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. tv_failure = (TextView) findViewById(R.id.tv_failure);
  10. tv_progress = (TextView) findViewById(R.id.tv_progress);
  11. pb = (ProgressBar) findViewById(R.id.pb);
  12. }
  13. public void click(View v){
  14. HttpUtils utils = new HttpUtils();
  15. String fileName = "QQPlayer.exe";
  16. //确定下载地址
  17. String path = "http://192.168.13.13:8080/" + fileName;
  18. utils.download(path, //下载地址
  19. "sdcard/QQPlayer.exe", //文件保存路径
  20. true,//是否支持断点续传
  21. true, new RequestCallBack<File>() {
  22. //下载成功后调用
  23. @Override
  24. public void onSuccess(ResponseInfo<File> arg0) {
  25. Toast.makeText(MainActivity.this, arg0.result.getPath(), 0).show();
  26. }
  27. //下载失败调用
  28. @Override
  29. public void onFailure(HttpException arg0, String arg1) {
  30. // TODO Auto-generated method stub
  31. tv_failure.setText(arg1);
  32. }
  33. @Override
  34. public void onLoading(long total, long current,
  35. boolean isUploading) {
  36. // TODO Auto-generated method stub
  37. super.onLoading(total, current, isUploading);
  38. pb.setMax((int)total);
  39. pb.setProgress((int)current);
  40. tv_progress.setText(current * 100 / total + "%");
  41. }
  42. });
  43. }
  44. }

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读