The use of Android development okhttp

Source: Internet
Author: User

This article records the use of the Okhttp framework in Android development. Okhttp is a library for network requests in Java, and the home page is: http://square.github.io/okhttp/, GitHub address: https://github.com/square/okhttp

The following describes the usage of the Okhttp library, this article will give Okhttp use Demo,demo contains common GET request, POST request, file upload and download, demo run effect as shown:


The following code one by one illustrates:

To use Okhttp, you must first import okhttp in your project, and in the Build.gradle file of the app module, add the following code:

dependencies {    Compile filetree (dir: ' Libs ', include: [' *.jar '])    testcompile ' junit:junit:4.12 '    compile ' com.android.support:appcompat-v7:23.1.1 '    compile ' com.squareup.okhttp3:okhttp:3.2.0 '}
This will import the okhttp into the project.

(1) Get request

The simplest use of GET requests is as follows:

Simple get request, without parameters public void Simplegetclick (view view) {    okhttpclient = new Okhttpclient ();    Request Request = new Request.builder ()            . URL ("http://192.168.1.170:8088/okhttp/test_simple_get.php")            . Build ();    Okhttpclient.newcall (Request). Enqueue (callback);}
If you want to add header headers and parameters to the request, you can do so in the following way:

Get request with parameter public void Addparamgetclick (view view) {    okhttpclient = new Okhttpclient ();    Request Request = new Request.builder ()            . AddHeader ("token", "Asdlfjkasdljfaskdjfalsjkljalk")  //Add parameters to the header            . URL ("http://192.168.1.170:8088/okhttp/test_param_get.php?username=zhangsan&phone=13888888888")//Carry Parameters            . Build ();    Okhttpclient.newcall (Request). Enqueue (callback);}

It should be noted that in the above code, callback is the callback interface after the request, the code is as follows:

Callback interface after request private Callback Callback = new Callback () {    @Override public    void OnFailure (called call, IOException e) {        Setresult (E.getmessage (), false);    }    @Override public    void Onresponse (call call, Response Response) throws IOException {        Setresult (Response.body (). String (), true);}    };
The callback interface needs to be aware that both Onresponse and onfailure are not executed in the UI thread, so if we want to do UI-related operations in Onresponse or onfailure, we need to do it in the UI thread.

(2) Post request

To compare a simple post request, use the following:

Simple post request with parameters and header public void Simplepostclick (view view) {    okhttpclient = new Okhttpclient ();    Requestbody requestbody = new Formbody.builder ()            . Add ("username", "Wangwu")            . Add ("Password", "hello12345")            . Add ("Gender", "female")            . Build ();    Request Request = new Request.builder ()            . URL ("http://192.168.1.170:8088/okhttp/test_simple_post.php")            . Post (Requestbody)            . AddHeader ("token", "Helloworldhelloworldhelloworld")            . Build ();    Okhttpclient.newcall (Request). Enqueue (callback);}
Here we need to construct a requestbody, then put the required parameters into the Requestbody, then use this requestbody to build a request, and finally put the request in the queue to execute

If our post request is slightly more complex, such as carrying a parameter that has both text and file types, you can request it in the following way:

//Post request with text parameters and file parameters Pu Blic void Filepostclick (view view) {Requestbody filebody = requestbody.create (mediatype.parse;    Charset=utf-8 "), tempfile); Requestbody requestbody = new Multipartbody.builder (). SetType (Multipartbody.form). Addformdatapart ( "username", "Wangwu"). Addformdatapart ("Password", "hello12345"). Addformdatapart ("Gender", "female"    ). Addformdatapart ("File", "Info.txt", Filebody). Build ();            Request Request = new Request.builder (). URL ("http://192.168.1.170:8088/okhttp/test_param_post.php")    . Post (Requestbody). AddHeader ("token", "Helloworldhelloworldhelloworld"). Build (); Okhttpclient.newcall (Request). Enqueue (callback);} 
In the above code, Tempfile is a text file, in order to post the file and some other parameters, we use Multipartbody to build a request body, it should be noted that because the post content contains files, so we must set for this request body Settype (Multipartbody.form)

(3) File upload

File upload and show progress, this code is slightly more complex, the following directly on the code:

Package Com.test.testokhttp;import Android.os.environment;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.widget.progressbar;import Android.widget.TextView; Import Android.widget.toast;import java.io.file;import java.io.ioexception;import java.util.concurrent.TimeUnit; Import OKHTTP3. Call;import OKHTTP3. Callback;import OKHTTP3. Interceptor;import OKHTTP3. Mediatype;import OKHTTP3. Multipartbody;import OKHTTP3. Okhttpclient;import OKHTTP3. Request;import OKHTTP3. Requestbody;import OKHTTP3. Response;import OKHTTP3. Responsebody;import Okio. Buffer;import Okio. Bufferedsink;import Okio. Bufferedsource;import Okio. Forwardingsink;import Okio. Forwardingsource;import Okio. Okio;import Okio. Sink;import Okio.    Source;public class Uploadactivity extends Appcompatactivity {private okhttpclient okhttpclient;    Private TextView Resulttextview;    Private ProgressBar ProgressBar;    Private File tempfile; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_upload);        Settitle ("Upload files and Show progress");        Resulttextview = (TextView) Findviewbyid (R.id.result_textview);        ProgressBar = (ProgressBar) Findviewbyid (R.id.progress_bar);        Progressbar.setmax (100); Okhttpclient = new Okhttpclient.builder (). ReadTimeout (timeunit.seconds). ConnectTimeout    (timeunit.seconds). WriteTimeout (Timeunit.seconds). build (); }//Click the button to start uploading the file public void Startuploadclick (view view) {tempfile = new file (Environment.getexternalstoragedi        Rectory (). GetAbsolutePath () + File.separator + "test.pdf"); Requestbody requestbody = new Multipartbody.builder (). SetType (multipartbody.form). Addformd Atapart ("File", "Test.pdf", Requestbody.create (Mediatype.parse ("application/pdf;   Charset=utf-8 "), Tempfile). Build ();     Progressrequestbody progressrequestbody = new Progressrequestbody (requestbody, Progresslistener);                Request Request = new Request.builder (). URL ("http://192.168.1.170:8088/okhttp/test_upload_file.php")        . Post (Progressrequestbody). build ();    Okhttpclient.newcall (Request). Enqueue (callback);        }//By implementing the method in the progress callback interface to show the progress of private progresslistener Progresslistener = new Progresslistener () {@Override public void update (long bytesread, long ContentLength, Boolean do) {int progress = (int) (100.0 * Bytesrea            D/contentlength);        Progressbar.setprogress (progress);    }    }; callback method after request private Callback Callback = new Callback () {@Override public void onfailure (called Call, Ioexce        Ption e) {Setresult (E.getmessage (), false); } @Override public void Onresponse (call call, Response Response) throws IOException {Setresult (r Esponse.body(). String (), true);    }    };            Shows the result of the request returned private void Setresult (Final String msg, final Boolean success) {Runonuithread (new Runnable () { @Override public void Run () {if (success) {Toast.maketext (uploadact                Ivity.this, "request succeeded", Toast.length_short). Show ();                } else {Toast.maketext (uploadactivity.this, "request Failed", Toast.length_short). Show ();            } resulttextview.settext (msg);    }        }); }//Custom requestbody, ability to show progress public class Progressrequestbody extends Requestbody {//actual to package request body private        Final Requestbody Requestbody;        Progress callback Interface private final Progresslistener Progresslistener;        Packaging completed Bufferedsink private bufferedsink bufferedsink; /** * constructor, Assignment * * @param requestbody request body to be packed * @param Progresslistener Callback interface * /Public Progressrequestbody (REQUESTBOdy requestbody, Progresslistener progresslistener) {this.requestbody = Requestbody;        This.progresslistener = Progresslistener; }/** * Rewrite calls the actual response body of CONTENTTYPE * * @return mediatype */@Override Pub        LIC mediatype ContentType () {return requestbody.contenttype ();          }/** * Overrides call the actual response body of ContentLength * * @return contentlength * @throws IOException exception */@Override public long ContentLength () throws IOException {return requestbody.content        Length ();        }/** * Rewrite to write * * @param sink Bufferedsink * @throws IOException Exception */                @Override public void WriteTo (Bufferedsink sink) throws IOException {if (Bufferedsink = = null) {            Packaging Bufferedsink = Okio.buffer (sink (sink)); }//write Requestbody.writeto (bUfferedsink);        Flush must be called, otherwise the last part of the data may not be written to Bufferedsink.flush (); }/** * Write, Callback Progress interface * * @param sink sink * @return sink */Private Sin  K Sink (sink sink) {return new Forwardingsink (sink) {//Current write byte number long Byteswritten                = 0L;                Total byte length, avoid multiple calls to the ContentLength () method Long contentlength = 0L; @Override public void Write (Buffer source, long ByteCount) throws IOException {SUPER.WR                    ITE (source, ByteCount); if (ContentLength = = 0) {//Get ContentLength value, subsequent calls to ContentLength = Content                    Length ();                    }//Increase the number of bytes currently written Byteswritten + = ByteCount;                Callback Progresslistener.update (Byteswritten, contentlength, Byteswritten = = contentlength); }            };    }}//Progress callback interface interface Progresslistener {void update (long bytesread, long contentlength, boolean done); }}
It is important to note that uploading a file requires implementing a custom requestbody, which is the progressrequestbody above, to get the upload progress in progressrequestbody.

(4) Download of the file

Download and upload similar, the difference is that we need to intern custom responsebody instead of Requestbody, the following code:

Import Android.os.environment;import Android.support.v7.app.appcompatactivity;import Android.os.Bundle;import Android.view.view;import Android.widget.progressbar;import Android.widget.textview;import android.widget.Toast; Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Java.util.concurrent.timeunit;import OKHTTP3. Call;import OKHTTP3. Callback;import OKHTTP3. Interceptor;import OKHTTP3. Mediatype;import OKHTTP3. Okhttpclient;import OKHTTP3. Request;import OKHTTP3. Response;import OKHTTP3. Responsebody;import Okio. Buffer;import Okio. Bufferedsource;import Okio. Forwardingsource;import Okio. Okio;import Okio.    Source;public class Downloadactivity extends Appcompatactivity {private okhttpclient okhttpclient;    Private TextView Resulttextview;    Private ProgressBar ProgressBar;    Private File tempfile;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); SetcontentvieW (r.layout.activity_download);        Settitle ("Download file and Show progress"); Okhttpclient = new Okhttpclient.builder (). Addnetworkinterceptor (New Interceptor () {@Ov Erride public Response Intercept (Interceptor.chain Chain) throws IOException {Response originalres                        Ponse = Chain.proceed (Chain.request ()); Return Originalresponse.newbuilder (). Body (New Progressresponsebody (Originalresponse.body ()                    , Progresslistener)). Build ();                 }}). connecttimeout (5, Timeunit.seconds). ReadTimeout (Timeunit.seconds)        . WriteTimeout (Timeunit.seconds). build ();        Resulttextview = (TextView) Findviewbyid (R.id.result_textview);        ProgressBar = (ProgressBar) Findviewbyid (R.id.progress_bar); Tempfile = new File (Environment.getexternalstoragedirectory (). GetAbsolutePath() + File.separator + system.currenttimemillis () + ". pdf"); }//download file public void Startdownloadclick (view view) {Request request = new Request.builder ().        URL ("Http://192.168.1.170:8088/okhttp/test.pdf"). Build ();    Okhttpclient.newcall (Request). Enqueue (callback); } private Progresslistener Progresslistener = new Progresslistener () {@Override public void update (long            Bytesread, Long ContentLength, Boolean done) {int progress = (int) (100.0 * bytesread/contentlength);        Progressbar.setprogress (progress);    }    }; callback method after request private Callback Callback = new Callback () {@Override public void onfailure (called Call, Ioexce        Ption e) {Setresult (E.getmessage (), false);  } @Override public void Onresponse (call call, Response Response) throws IOException {if (Response ! = NULL) {//download complete, save data to file InputStream is = Response.body (). ByteStream ();                FileOutputStream fos = new FileOutputStream (tempfile);                byte[] buf = new byte[1024];                int hasread = 0;                while ((Hasread = Is.read (buf)) > 0) {fos.write (buf, 0, Hasread);                } fos.close ();                Is.close ();            Setresult ("Download succeeded", true);    }        }    };            Shows the result of the request returned private void Setresult (Final String msg, final Boolean success) {Runonuithread (new Runnable () { @Override public void Run () {if (success) {Toast.maketext (Downloada                Ctivity.this, "request succeeded", Toast.length_short). Show ();                } else {Toast.maketext (downloadactivity.this, "request Failed", Toast.length_short). Show ();            } resulttextview.settext (msg);    }        }); }//Custom responsebody, in which process progress private static class ProgressresponseboDY extends Responsebody {private final responsebody responsebody;        Private final Progresslistener Progresslistener;        Private Bufferedsource Bufferedsource;  Public Progressresponsebody (Responsebody responsebody, Progresslistener progresslistener) {this.responseBody =            Responsebody;        This.progresslistener = Progresslistener;        } @Override Public MediaType ContentType () {return responsebody.contenttype ();        } @Override public Long ContentLength () {return responsebody.contentlength ();  } @Override Public Bufferedsource source () {if (Bufferedsource = = null) {Bufferedsource            = Okio.buffer (Source (Responsebody.source ()));        } return Bufferedsource; } private Source Source (source source) {return new Forwardingsource (source) {Long total                Bytesread = 0L; @Override public Long Read (Buffer sInk, long ByteCount) throws IOException {Long bytesread = Super.read (sink, byteCount);                    Read () returns the number of bytes read, or-1 If this source is exhausted. Totalbytesread + = bytesread! =-1?                    bytesread:0;                    Progresslistener.update (Totalbytesread, Responsebody.contentlength (), bytesread = =-1);                return bytesread;        }            };    }}//Progress callback interface interface Progresslistener {void update (long bytesread, long contentlength, boolean done); }}
If we use the above code directly in the project to make HTTP requests, it is bound to be troublesome, so here we need to encapsulate the above code, as far as possible in the project with a short code to complete the network request. In addition, there must be a lot of network requests in a project, and we don't have to create a Okhttpclient object in every network request, and all of the requests are shared by a okhttpclient.

Reference: http://blog.csdn.net/lmj623565791/article/details/47911083

Demo download





The use of Android development okhttp

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.