Android Network Programming-using HttpClient to upload files in batches (2) AsyncTask + HttpClient and implement upload progress monitoring,
Please respect the fruits of others' work, and repost them with the source:
Android Network Programming-using HttpClient to batch upload files (2) AsyncTask + HttpClient and implement upload progress listening
Run:
I once introduced how to use HttpClient to upload files in batch in Android Network ProgrammingHttpClientMultifile upload and server receiving. Used in the previous articleHandler + HttpClientTo upload files. This article introduces how to useAsyncTask + HttpClientImplements file upload and monitors the upload progress.
Monitoring progress implementation:
First, define the listener interface. As follows:
/*** Progress listener interface */public interface ProgressListener {public void transferred (longtransferedBytes );}
The key part of the implementation of monitoring progress is to record the number of transmitted bytes, so we need to reloadFilterOutputStream, Override the key method to implement the progress listening function, as shown below. In this example, the first reload isHttpEntityWrapperAs the name suggests, it means to sendHttpEntityTo calculate the total number of bytes, the Code is as follows:
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: indicates the number of bytes sent when the output stream (OutputStream) * @ author JPH * Date: 2014.11.03 */public class ProgressOutHttpEntity extends HttpEntityWrapper {/** progress listener object **/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; listener (final OutputStream out, final ProgressListener listener) {super (out); this. listener = listener; this. transfer Red = 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);}/*** progress listener interface */public interface ProgressListener {public void transferred (long transferedBytes );}}
Finally, it is very simple to use the class and Httpclient implemented above to upload and display the progress. The Code is as follows: Use AsyncTask for asynchronous upload.
/*** Use AsyncTask + HttpClient to upload files asynchronously. Multifile upload is supported and the upload progress is displayed * @ author JPH * Date: 2014.10.09 * last modified 2014.11.03 */public class UploadUtilsAsync extends AsyncTask <String, Integer, String> {/** server path **/private String url; /** upload parameters **/private Map <String, String> paramMap;/** files to be uploaded **/private ArrayList <File> files; private long totalSize; private Context context; private ProgressDialog progressDialog; public uploadui LsAsync (Context context, String url, Map <String, String> paramMap, ArrayList <File> files) {this. context = context; this. url = url; this. paramMap = paramMap; this. files = files ;}@ Overrideprotected void onPreExecute () {// initialization before execution // TODO Auto-generated method stubprogressDialog = new ProgressDialog (context); progressDialog. setTitle ("Please wait... "); progressDialog. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); progressDialog. SetCancelable (true); progressDialog. show (); super. onPreExecute () ;}@ Overrideprotected String doInBackground (String... params) {// execute the task // TODO Auto-generated method stubMultipartEntityBuilder builder = MultipartEntityBuilder. create (); builder. setCharset (Charset. forName (HTTP. UTF_8); // sets the Request Encoding format builder. setMode (HttpMultipartMode. BROWSER_COMPATIBLE); // sets the browser compatibility mode int count = 0; for (File file: files) {// FileBody FileBody = new FileBody (file); // converts a file into a stream object FileBody // builder. addPart ("file" + count, fileBody); builder. addBinaryBody ("file" + count, file); count ++;} builder. addTextBody ("method", paramMap. get ("method"); // sets the request parameter builder. addTextBody ("fileTypes", paramMap. get ("fileTypes"); // sets the request parameter HttpEntity entity = builder. build (); // generate the http post object totalSize = entity. getContentLength (); // get the size of the uploaded file ProgressOutHttpEntity p Updated = new ProgressOutHttpEntity (entity, new ProgressListener () {@ Override public void transferred (long transferedBytes) {publishProgress (int) (100 * transferedBytes/totalSize )); // Update Progress}); return uploadFile (url, progressHttpEntity);} @ Overrideprotected void onProgressUpdate (Integer... values) {// execution progress // TODO Auto-generated method stubLog. I ("info", "values:" + values [0]); progressDi Alog. setProgress (int) values [0]); // update progress bar super. onProgressUpdate (values) ;}@ Overrideprotected void onPostExecute (String result) {// execution result // TODO Auto-generated method stubLog. I ("info", result); Toast. makeText (context, result, Toast. LENGTH_LONG ). show (); progressDialog. dismiss (); super. onPostExecute (result);}/*** upload a file to the server * @ param url * @ param entity * @ return */public String uploadFile (String url, Progres SOutHttpEntity entity) {HttpClient httpClient = new DefaultHttpClient (); // enable a client HTTP request httpClient. getParams (). setParameter (CoreProtocolPNames. PROTOCOL_VERSION, HttpVersion. HTTP_1_1); httpClient. getParams (). setParameter (CoreConnectionPNames. CONNECTION_TIMEOUT, 5000); // sets the connection timeout value HttpPost httpPost = new HttpPost (url); // creates an http post request httpPost. setEntity (entity); try {HttpResponse httpResponse = ht TpClient.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {return "File Uploaded successfully";} catch (ClientProtocolException e) {e. printStackTrace ();} catch (ConnectTimeoutException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} finally {if (httpClient! = Null & httpClient. getConnectionManager ()! = Null) {httpClient. getConnectionManager (). shutdown () ;}} return "File Upload Failed ";}}
For more information about how to receive files from the server, see HttpClient batch Upload File for Android Network Programming.
If you think this blog post is helpful to you, please give it a compliment! You can also follow fengyuzhengfan's blog to learn more! Http://blog.csdn.net/fengyuzhengfan/