Android network programming using HttpClient bulk upload files (ii) Asynctask+httpclient and implement upload progress monitoring

Source: Internet
Author: User

Please respect other people's labor results, reproduced please specify the source:  

Android Network programming using HttpClient bulk upload files (ii) Asynctask+httpclient and implement upload progress monitoring

Run:


I have described how to use the HttpClient bulk upload file in theAndroid Network programming article to HttpClient Implement multi-file uploads and server reception. In the previous article mainly use handler+httpclient Way to achieve file upload. This article describes using asynctask+httpclient to implement file uploads and monitor upload progress.

Monitor Progress implementation:

First define the listener interface. As shown below:

/** * Progress Listener Interface */public interface Progresslistener {public    void transferred (longtransferedbytes);}

The key part of implementing monitoring progress is to record the number of bytes transferred, so we need to overload Filteroutputstream, rewrite the key method, implement the function of progress monitoring, as shown below, the first overload in this example is Httpentitywrapper, as the name implies, is to package the httpentity to be sent, in order to 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: Output stream (OutputStream) The number of bytes sent is recorded * @author JPH * date:2014.11.03 */public class Progressouthttpentity extends Httpentitywrapper {/    * * Progress Monitoring 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;            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));     }/** * Progress Listener Interface */public interface Progresslistener {public void transferred (long transferedbytes); }}

Finally, using the above implemented classes and httpclient to upload and display the progress of the function, very simple, the code is as follows, using Asynctask asynchronous upload.

/** * Asynchronous Asynctask+httpclient upload file, support multi-file upload, and display upload progress * @author JPH * date:2014.10.09 * Last modified 2014.11.03 */public class Uploadutilsasync extends Asynctask<string, Integer, string>{/** server path **/private String url;/** uploaded parameters **/private map<string,string>parammap;/** files to upload **/private arraylist<file>files;private long totalSize;private Context Context;private ProgressDialog Progressdialog;public uploadutilsasync (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 () {//Pre-execution initialization//TODO auto-generated method Stubprogressdialog=new ProgressDialog ( Context);p Rogressdialog.settitle ("Please wait ...");p Rogressdialog.setprogressstyle (progressdialog.style_horizontal); Progressdialog.setcancelable (True);p rogressdialog.show (); Super.onpreexecute ();} @Overrideprotected string Doinbackground (String ... params) {//Perform task//TODO auto-generated method StubmultIpartentitybuilder builder = multipartentitybuilder.create (); Builder.setcharset (Charset.forname (HTTP. Utf_8));//Set the requested encoding format Builder.setmode (httpmultipartmode.browser_compatible);//Set browser compatibility mode int count=0;for (file file: files) {//filebody filebody = new Filebody (file);//convert file to stream object Filebody//builder.addpart ("file" +count, filebody); Builder.addbinarybody ("File" +count, file); count++;} Builder.addtextbody ("Method", Parammap.get ("method"));//Set request parameter Builder.addtextbody ("FileTypes", Parammap.get (" FileTypes "));//Set request parameter httpentity entity = Builder.build ();//Generate HTTP POST entity totalsize = Entity.getcontentlength ();//Get Upload                     File size progressouthttpentity progresshttpentity = new progressouthttpentity (Entity, new Progresslistener () { @Override public void transferred (long transferedbytes) {PU        Blishprogress ((int) (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]);p rogressdialog.setprogress ((int) values[0]);//Update progress bar super.onprogressupdate (values);} @Overrideprotected void OnPostExecute (String result) {//Execute result//TODO auto-generated method stublog.i ("info", result); Toast.maketext (context, result, Toast.length_long). Show ();p Rogressdialog.dismiss (); Super.onpostexecute (result);  /** * Uploading files to server * @param URL * @param entity * @return */public string uploadfile (string url, progressouthttpentity entity) {HttpClient httpclient=new defaulthttpclient ();//Open a client HTTP request Httpclient.getparams (). Setparameter (Coreprotoco        Lpnames.protocol_version, httpversion.http_1_1); Httpclient.getparams (). Setparameter (Coreconnectionpnames.connection_timeout, 5000);//Set connection time-out httppost HttpPost =        New HttpPost (URL);//Create an HTTP POST request httppost.setentity (entity); try {httpresponse HttpResponse = HttpcLient.execute (HttpPost);            if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {return "file upload succeeded";        }} catch (Clientprotocolexception e) {e.printstacktrace ();        } catch (Connecttimeoutexception e) {e.printstacktrace ();        } catch (Exception e) {e.printstacktrace (); } finally {if (httpClient! = null && Httpclient.getconnectionmanager ()! = null) {HTTPC            Lient.getconnectionmanager (). Shutdown ();    }} return "File upload failed"; }}

On the server side how to receive: You can refer to: "Android network programming using httpclient batch upload files ," I have introduced in the very clear.

If you think this blog post is helpful to you, please give this blog a praise! You can also pay attention to Fengyuzhengfan's blog, watch more wonderful!http://blog.csdn.net/fengyuzhengfan/

Android network programming using HttpClient bulk upload files (ii) Asynctask+httpclient and implement upload progress monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.