Android Network Programming-using HttpClient to batch upload files (2) AsyncTask + HttpClient and implement upload progress listening
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.
/*** Asynchronous AsyncTask + HttpClient: supports Multifile upload and displays the upload progress * @ author JPH * Date: 2014.10.09 * last modified 2014.11.03 */public class UploadUtilsAsync extends AsyncTask
{/** Server path **/private String url;/** uploaded parameter **/private Map
ParamMap;/** file to be uploaded **/private ArrayList
Files; private long totalSize; private Context context; private ProgressDialog progressDialog; public UploadUtilsAsync (Context context, String url, Map
ParamMap, ArrayList
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 () ;}@ Overrideprote Cted 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 ); // convert the 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 progressHttpEntity = 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]); progressDialog. setProgress (int) values [0]); // update progress bar super. onProgressUpdate (values) ;}@ Overri Deprotected 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, ProgressOutHttpEntity entity) {HttpClient httpClient = new DefaultHttpClient (); // start a customer 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 = httpClient.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/