Android 网络编程使用httpClient批量上传文件并监听进度

运行效果图:
Android 网络编程使用httpClient批量上传文件并监听进度_第1张图片
AsyncTask+HttpClient并实现上传进度监听

我曾在《 Android 网络编程之使用HttpClient 批量上传文件 》一文中介绍过如何通过 HttpClient 实现多文件上传和服务器的接收。在上一篇主要使用 Handler+HttpClient 的方式实现文件上传。这一篇将介绍使用 AsyncTask+HttpClient 实现文件上传并监听上传进度。

监控进度实现:

首先定义监听器接口。如下所示:

/**
* 进度监听器接口
*/
public interface ProgressListener {
public void transferred(longtransferedBytes);
}
实现监控进度的关键部分就在于记录已传输字节数,所以我们需重载 FilterOutputStream ,重写其中的关键方法,实现进度监听的功能,如下所示,本例中首先重载的是 HttpEntityWrapper ,顾名思义,就是将需发送的 HttpEntity 打包,以便计算总字节数,代码如下:

package com.jph.ufh.utils;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;

/**
* ProgressOutHttpEntity:输出流(OutputStream)时记录已发送字节数
* @author JPH
* Date:2014.11.03
*/
public class ProgressOutHttpEntity extends HttpEntityWrapper {
/进度监听对象/
private final ProgressListener listener;
public ProgressOutHttpEntity(final HttpEntity entity,final ProgressListener listener) {
super(entity);
this.listener = listener;
}

public static class CountingOutputStream extends FilterOutputStream {

private final ProgressListener listener;
private long transferred;

CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}

@Override
public void write(final byte[] b, final int off, final int len)
throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}

@Override
public void write(final int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}

}

@Override
public void writeTo(final OutputStream out) throws IOException {

this.wrappedEntity.writeTo(out instanceof CountingOutputStream ? out
: new CountingOutputStream(out, this.listener));
}
/**
* 进度监听器接口
*/
public interface ProgressListener {
public void transferred(long transferedBytes);
}
}
最后就是使用上述实现的类和Httpclient进行上传并显示进度的功能,非常简单,代码如下,使用AsyncTask异步上传。

/**
* 异步AsyncTask+HttpClient上传文件,支持多文件上传,并显示上传进度
* @author JPH
* Date:2014.10.09
* last modified 2014.11.03
*/
public class UploadUtilsAsync extends AsyncTask

你可能感兴趣的:(android,AsyncTask)