Using Android's Okhttp package to implement file upload downloads based on HTTP protocol _android

Source: Internet
Author: User
Tags file upload file url http request md5

Okhttp HTTP Connection Basics
Although you only need to provide a URL when sending an HTTP request using Okhttp, Okhttp needs to consider 3 different elements in the implementation to determine which HTTP connection is actually established between the HTTP servers. This is done to achieve the best performance.
The first element to consider first is the URL itself. The URL gives the path to the resource to be accessed. For example, URL http://www.baidu.com is the corresponding Baidu homepage of the HTTP document. The more important part of the URL is the mode that is used when accessing, that is, HTTP or HTTPS. This determines whether the Okhttp establishes a clear-text HTTP connection or an encrypted HTTPS connection.
The second element is the address of the HTTP server, such as baidu.com. Each address has a corresponding configuration, including port number, HTTPS connection settings, and network transport protocol. URLs on the same address can share the same underlying TCP socket connection. A shared connection can have a significant performance boost. The okhttp provides a connection pool rifle connection.
The third element is the route to use when connecting to an HTTP server. Routes include the IP addresses of specific connections (found through DNS queries) and the proxy servers used. For HTTPS connections, also includes the version of TLS used for communication negotiation. There may be several different routes for the same address. Okhttp automatically tries an alternate route when it encounters an access error.
When a URL is requested through Okhttp, Okhttp first obtains the address information from the URL and then obtains the connection from the connection pool based on the address. If no connection is found in the connection pool, select a route to try the connection. Trying to connect requires a DNS query to get the server's IP address, and also uses information such as proxy server and TLS version. When the actual connection is established, Okhttp sends the HTTP request and gets the response. When there is a problem with the connection, Okhttp automatically chooses another route to try. This allows okhttp to automatically handle network problems that may arise. When a response to an HTTP request is successfully obtained, the current connection is put back into the connection pool and provided for subsequent requests. The connection pool periodically closes idle connections to free up resources.

File upload and download examples:
1. upload files without parameters

  /** * Upload file * @param actionurl interface address * @param filePath Local File Address * * Public <T> void UploadFile (String ac Tionurl, String filePath, Final reqcallback<t> callBack) {//full complement request address String Requesturl = String.Format ("%s/%s
    ", Base_url, ActionURL);
    Create File File = new file (FilePath);
    Create Requestbody Requestbody BODY = requestbody.create (media_object_stream, file);
    Create request final Request request = new Request.builder (). URL (requesturl). Post (body). Build ();
    Final Call call = Mokhttpclient.newbuilder (). WriteTimeout (Timeunit.seconds). Build (). Newcall (Request); Call.enqueue (New Callback () {@Override public void onfailure (call call, IOException e) {log.e (TAG, E
        . toString ());
      Failedcallback ("Upload failed", callBack); @Override public void Onresponse (call call, Response Response) throws IOException {if (response.is
  Successful ()) {String string = Response.body (). String ();        LOG.E (TAG, "response----->" + string);
        Successcallback ((T) string, callBack);
        else {failedcallback ("Upload failed", callBack);
  }
      }
    });

 }

2. Upload files with parameters

/** * Upload file * @param actionurl interface address * @param paramsmap parameter * @param callBack callback * @param <T> * PU Blic <t>void UploadFile (String actionurl, hashmap<string, object> Paramsmap, Final reqcallback<t>
      CallBack) {try {//Fill full request address String Requesturl = String.Format ("%s/%s", Upload_head, ActionURL);
      Multipartbody.builder Builder = new Multipartbody.builder ();
      Set type Builder.settype (Multipartbody.form);
        Append parameter for (String Key:paramsMap.keySet ()) {object = Paramsmap.get (key); if (!) (
        Object instanceof File) {Builder.addformdatapart (key, object.tostring ());
          else {File File = (file) object;
        Builder.addformdatapart (Key, File.getname (), requestbody.create (null, file));
      }//Create requestbody Requestbody BODY = Builder.build (); Create request final Request request = new Request.builder (). URL (requesturl). Post (body). BuilD (); Set parameters individually such as read timeout final call = Mokhttpclient.newbuilder (). WriteTimeout (+ timeunit.seconds). Build (). Newcall (re
      Quest); Call.enqueue (New Callback () {@Override public void onfailure (call call, IOException e) {LOG.E (
          TAG, e.tostring ());
        Failedcallback ("Upload failed", callBack); @Override public void Onresponse (call call, Response Response) throws IOException {if (respo
            Nse.issuccessful ()) {String string = Response.body (). String ();
            LOG.E (TAG, "response----->" + string);
          Successcallback ((T) string, callBack);
          else {failedcallback ("Upload failed", callBack);
    }
        }
      });
    catch (Exception e) {log.e (TAG, e.tostring ());

 }
  }

3. Upload file with parameter with progress

 /** * Upload file * @param actionurl interface address * @param paramsmap parameter * @param callBack callback * @param <T> * p Ublic <T> void UploadFile (String actionurl, hashmap<string, object> Paramsmap, Final reqprogresscallback
      <T> callBack) {try {//Fill full request address String Requesturl = String.Format ("%s/%s", Upload_head, ActionURL);
      Multipartbody.builder Builder = new Multipartbody.builder ();
      Set type Builder.settype (Multipartbody.form);
        Append parameter for (String Key:paramsMap.keySet ()) {object = Paramsmap.get (key); if (!) (
        Object instanceof File) {Builder.addformdatapart (key, object.tostring ());
          else {File File = (file) object;
        Builder.addformdatapart (Key, File.getname (), Createprogressrequestbody (media_object_stream, file, CallBack));
      }//Create requestbody Requestbody BODY = Builder.build (); Create request final Request request = new Request.
      Builder (). URL (requesturl). Post (body). Build ();
      Final Call call = Mokhttpclient.newbuilder (). WriteTimeout (Timeunit.seconds). Build (). Newcall (Request); Call.enqueue (New Callback () {@Override public void onfailure (call call, IOException e) {LOG.E (
          TAG, e.tostring ());
        Failedcallback ("Upload failed", callBack); @Override public void Onresponse (call call, Response Response) throws IOException {if (respo
            Nse.issuccessful ()) {String string = Response.body (). String ();
            LOG.E (TAG, "response----->" + string);
          Successcallback ((T) string, callBack);
          else {failedcallback ("Upload failed", callBack);
    }
        }
      });
    catch (Exception e) {log.e (TAG, e.tostring ());

 }
  }

4. Create a requestbody with progress

 /** * Create requestbody with PROGRESS * @param contentType mediatype * @param file ready to upload files * @param callBack callback * @para  M <T> * @return/public <T> Requestbody createprogressrequestbody (final mediatype ContentType, final File file, final reqprogresscallback<t> callBack) {return new Requestbody () {@Override public Med
      Iatype ContentType () {return contentType;
      @Override public Long ContentLength () {return file.length ();
        @Override public void WriteTo (Bufferedsink sink) throws IOException {source source;
          try {Source = Okio.source (file);
          Buffer buf = new buffer ();
          Long remaining = ContentLength ();
          Long current = 0; for (long readcount; (Readcount = Source.read (buf, 2048))!=-1;
            ) {Sink.write (buf, readcount);
            Current + = Readcount;
         LOG.E (TAG, "current------>" + current);   Progresscallback (remaining, current, callBack);
        } catch (Exception e) {e.printstacktrace ();
  }
      }
    };

 }

5. Download    without a progress file;

 /** * Download File * @param fileUrl file URL * @param destfiledir storage target directory/public <T> void DownLoadFile (String FILEURL, final string destfiledir, final reqcallback<t> callBack) {final string fileName = Md5.encode (FILEURL)
    ;
    Final file File = new file (Destfiledir, fileName);
      if (file.exists ()) {Successcallback ((T) file, callBack);
    Return
    Final Request request = new Request.builder (). URL (fileUrl). build ();
    Final Call call = Mokhttpclient.newcall (request); Call.enqueue (New Callback () {@Override public void onfailure (call call, IOException e) {log.e (TAG, E
        . toString ());
      Failedcallback ("Download Failed", callBack); @Override public void Onresponse (call call, Response Response) throws IOException {InputStream is
        = NULL;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
  try {Long total = Response.body (). ContentLength ();        LOG.E (TAG, "total------>" + total);
          Long current = 0;
          is = Response.body (). ByteStream ();
          FOS = new FileOutputStream (file);
            while (len = Is.read (buf))!=-1) {current + = Len;
            Fos.write (buf, 0, Len);
          LOG.E (TAG, "current------>" + current);
          } fos.flush ();
        Successcallback ((T) file, callBack);
          catch (IOException e) {log.e (TAG, e.tostring ());
        Failedcallback ("Download Failed", callBack);
            Finally {try {if (is!= null) {is.close ();
            } if (fos!= null) {fos.close ();
          The catch (IOException e) {log.e (TAG, e.tostring ());
  }
        }
      }
    });

 }

6. Download with progress file

 /** * Download File * @param fileUrl file URL * @param destfiledir storage target directory/public <T> void DownLoadFile (String FILEURL, final string destfiledir, final reqprogresscallback<t> callBack) {final string fileName = Md5.encode (
    FILEURL);
    Final file File = new file (Destfiledir, fileName);
      if (file.exists ()) {Successcallback ((T) file, callBack);
    Return
    Final Request request = new Request.builder (). URL (fileUrl). build ();
    Final Call call = Mokhttpclient.newcall (request); Call.enqueue (New Callback () {@Override public void onfailure (call call, IOException e) {log.e (TAG, E
        . toString ());
      Failedcallback ("Download Failed", callBack); @Override public void Onresponse (call call, Response Response) throws IOException {InputStream is
        = NULL;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null; try {Long total = Response.body (). ContentlengTh ();
          LOG.E (TAG, "total------>" + total);
          Long current = 0;
          is = Response.body (). ByteStream ();
          FOS = new FileOutputStream (file);
            while (len = Is.read (buf))!=-1) {current + = Len;
            Fos.write (buf, 0, Len);
            LOG.E (TAG, "current------>" + current);
          Progresscallback (total, Current, callBack);
          } fos.flush ();
        Successcallback ((T) file, callBack);
          catch (IOException e) {log.e (TAG, e.tostring ());
        Failedcallback ("Download Failed", callBack);
            Finally {try {if (is!= null) {is.close ();
            } if (fos!= null) {fos.close ();
          The catch (IOException e) {log.e (TAG, e.tostring ());
  }
        }
      }
    });

 }
7. Interface Reqprogresscallback.java Implementation
Public interface reqprogresscallback<t> extends reqcallback<t>{
  /**
   * Response Progress update
   /
  void OnProgress (long, long current);
}
8. Progress Callback Implementation
  /**
   * Unified Processing Progress Information
   * @param  Total size
   * @param current Progress
   * @param callBack
   * @param <t& gt;
   *
  private <T> void Progresscallback (Final long total, final long, final reqprogresscallback<t> CallBack) {
    okhttphandler.post (new Runnable () {
      @Override public
      void Run () {
        if (callBack!= null) {
          callback.onprogress (total, current);}}}
    );
  

Related Article

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.