The article Outlines

OkHttp brief introduction two, OkHttp simple use three, OkHttp package four, project source download

Introduction to OkHttp

1. What is OkHttp

Typically on the Java platform, we use Apache HttpClient as the Http client to send Http requests and process the responses. For example, HTTP clients can be used to integrate with third-party services (such as SSO services), and of course, to crawl data on the web. OKHttp is an Http client similar to HttpClient, providing support for Http /2 and SPDY, as well as connection pooling, GZIP compression, and Http response caching.

2. OkHttp advantages

(1) Support HTTP2/SPDY (SPDY is a TCP based protocol developed by Google, used to minimize network latency, improve network speed, optimize user network experience) (2) Automatic socket selection of the best route, and support automatic reconnection, with automatic maintenance of socket connection pool, (3) Reduce the number of repeated network requests based on Headers. (4) Have Interceptors easily handle requests and responses (automatically handle GZip compression)

3. OkHttp function

(1) General GET request (2) General POST request (3) HTTP-based file upload (4) File download (5) Upload and download progress callback (6) load picture (7) Support request callback, Directly return object, object collection (8) support session persistence (9) support HTTPS access to self-signed websites, provide method Settings under the certificate (10) support to cancel a requestCopy the code

3. OkHttp usage steps

(1) The step of get Request, first construct a Request object, the parameter at least has a URL, of course you can use request. Builder to set more parameters such as: header, method, etc. (2) Then construct a Call object from the request object, which is similar to encapsulating your request into a task. Since it is a task, there will be execute() and cancel() methods. (3) Finally, we want to execute the request asynchronously, so we call call.enqueue, add the call to the scheduling queue, and wait for the task to complete, we can get the result in Callback. (4) The onResponse callback takes response. In general, if we want to get the returned string, we can get response.body().string(). If you want an array of binary bytes returned, call response.body().bytes(); If you want to get the returned inputStream, call Response.body ().bytestream () (5). If you see this, you might be surprised that you can get the returned inputStream at all. With inputStream we can write files by IO. But the onResponse thread is not the UI thread. OkHttp supports both synchronous and asynchronous requests. Call Call = client. NewCall (Request); Call.enqueue (new Callback()); call.enqueue(new Callback()); call.enqueue(new Callback(); Call.Cancel () can be executed either inside onFailure or onResponse methods. To cancelAll requests, okhttpclient.dispatcher().cancelall ();

OkHttp is easy to use

1. Make a GET request

/** * The original get request **@authorWu Xiao-chang * */
public class OkHttpGet {

    public void get(a) {

         / / 1. OkhttpClient object
        OkHttpClient okHttpClient = new OkHttpClient.Builder().
                // In this case, you can also set up data caching, etc
                // Set the timeout period
                connectTimeout(15, TimeUnit.SECONDS).
                readTimeout(20, TimeUnit.SECONDS).
                writeTimeout(20,  TimeUnit.SECONDS).
                // Error reconnection
                retryOnConnectionFailure(true).
                build();

        / / 2 construction Request,
        //builder.get() represents a get request, and the url is a network address
        Request.Builder builder = new Request.Builder();

        Request request = builder.get().url("http://www.baidu.com/").build();

        //3 Encapsulate Request as call
        Call call = okHttpClient.newCall(request);

        //4, execute call, which requests data asynchronously
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {

                // Failed to call
            }

            @Override
            // Because OkHttp depends on the Content-Type field in the response header to determine the decoding method when parsing the response
            //OkHttp will be decoded using the default UTF-8 encoding
            // Asynchronous loading is used here. If controls are needed, they are called in the main thread
            public void onResponse(Call arg0, Response arg1) throws IOException {

                 // Successful call}}); }}Copy the code

2. Make a POST request

/** * Use okhttp for post requests **@authorWu Xiao-chang * */
public class OkHttpPost {

    public void initPost(a) {

        / / 1. OkhttpClient object
        OkHttpClient okHttpClient = new OkHttpClient.Builder().
                // In this case, you can also set up data caching, etc
                // Set the timeout period
                connectTimeout(15, TimeUnit.SECONDS).
                readTimeout(20, TimeUnit.SECONDS).
                writeTimeout(20,  TimeUnit.SECONDS).
                // Error reconnection
                retryOnConnectionFailure(true).
                build();

         RequestBody requestBodyPost = new FormBody.Builder()
         .add("page"."1")
         .add("code"."news")
         .add("pageSize"."20")
         .add("parentid"."0")
         .add("type"."1")
         .build();

         Request requestPost = new Request.Builder()
         .url("www.baidu.com")
         .post(requestBodyPost)
         .build();

         okHttpClient.newCall(requestPost).enqueue(new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {

                //okHttp also supports GJson processing
                // List
      
        and bean processing can be done here
      }}); }}Copy the code

3. Upload and download pictures

/** * Upload and download images using OkHttp **@authorWu Xiao-chang * */
public class OkHttpPicture 
{

    public void getPicture(a) {

         Create an okHttpClient object
         OkHttpClient okHttpClient = new OkHttpClient();  

         // Create a Request.Builder object and set parameters. If the Request type is Get, do not set parameters
         Request request = new Request.Builder()  
                .url("www.baidu.com")  
                .build();  

         //3. Create a Call object with a request object and send the request
         Call call = okHttpClient.newCall(request);  

         //4. Asynchronous request to join scheduling
         call.enqueue(new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {

// // get get resources from the Internet and convert them to the type we want
// byte[] Picture_bt = response.body().bytes();
// // Update the UI using the handler
// Message message = handler.obtainMessage();
// message.obj = Picture_bt;
// message.what = SUCCESS;
// handler.sendMessage(message);}}); }public void shangChuanPicture(a) {

        OkHttpClient mOkHttpClent = new OkHttpClient();

        // Get the file from the SD card
        File file = new File(Environment.getExternalStorageDirectory()+"/HeadPortrait.jpg");

        MultipartBody.Builder builder = new MultipartBody.Builder()
                // Set the type
                .setType(MultipartBody.FORM)
                // Set the body content
                .addFormDataPart("img"."HeadPortrait.jpg",
                        RequestBody.create(MediaType.parse("image/png"), file));

        RequestBody requestBody = builder.build();

        Request request = new Request.Builder()
                .url("www.baidu.com") .post(requestBody) .build(); Call call = mOkHttpClent.newCall(request); }}Copy the code

3. Interceptor use

What is an interceptor First we need to know what an interceptor is. For example, biaoju escorted a box of gold ingot walking on a mountain path, suddenly from the mountain down a mountain thieves stopped biaoju road, biaoju body valuable things after the clean will release. The robber is the interceptor, and the biaoju is a network request that is performing a task, and the parameters in the request are the ingot carried by biaoju. The interceptor can validate the parameters carried by the network request and then release it. This actually designed the idea of AOP programming (faceted programming). Before we get into the role and benefits of interceptors, let’s go back to the role of the bandit. If you were a bandit, where would you ambush? Must have been ambushed in the path of red Dead redemption. In other words, the interceptor intercepts all network requests in the path of the interception. (1) Interceptors can modify all requests and return values at once. (2) The interceptor can encode the parameters and results of the request once, such as utF-8. (3) The interceptor can log all requests uniformly, without having to add a log operation at the beginning or end of each request. (4) Other requirements that require unified processing of requests and returns… .

Interceptors in OkHttp are classified into two categories: An Application Interception is an Application Interception for an Application and an Application Interception for a Network request. 1) You do not need to worry about whether the OkHttp request policy and request speed will be affected. 2) The Application interceptor is executed even if the data is fetched from the cache. 3) Allow retries, that is, chain.proceed () can be executed more than once. Network Interception allows you to modify some of the attributes automatically added by the OkHttp framework before connecting to the Network. 2) Can observe the final complete request parameters (that is, the final server received the request data and familiar)

For those of you who are not familiar with interceptors, you are advised to use an Application Interception. This avoids breaking the OkHttp request policy.

Common scenarios (1) Encrypt request parameters in a unified manner. (2) Block the URL that does not comply with the rule. (3) Set uniform encoding for request or return parameters (4) Other… .

The code field

public class OkHttpLanJieQi {

    /** * Apply interceptor */
    Interceptor appInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();

            // -- Things to do before requesting ————
            HttpUrl url = request.url();
            String s = url.url().toString();

            Response response = chain.proceed(request);

            // -- do something after the request ————
            Log.d("aa"."app interceptor:begin");

            returnresponse; }};/** * Network interceptor */
    Interceptor networkInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            // -- Things to do before requesting ————

            Response  response = chain.proceed(request);

          // -- do something after the request ————

            returnresponse; }};/** * make get requests and configure interceptors */
    public void initGet(a) {

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(appInterceptor)/ / Application interceptors
                .addNetworkInterceptor(networkInterceptor)/ / Network interceptor
                .build();

        / / 2 construction Request,
        //builder.get() represents a get request, and the url is a network address
        Request.Builder builder = new Request.Builder();

        Request request = builder.get().url("http://www.baidu.com/").build();

        //3 Encapsulate Request as call
        Call call = okHttpClient.newCall(request);

        //4, execute call, which requests data asynchronously
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {

                // Failed to call
            }

            @Override
            // Because OkHttp depends on the Content-Type field in the response header to determine the decoding method when parsing the response
            //OkHttp will be decoded using the default UTF-8 encoding
            // Asynchronous loading is used here. If controls are needed, they are called in the main thread
            public void onResponse(Call arg0, Response arg1) throws IOException {

                 // Successful call}}); }}Copy the code

OkHttp encapsulation

1. Simple packaging by itself

/** * okhttp operation to encapsulate **@authorWu Xiao-chang * */
public class OkHttp {

    public void get(String url, Callback callback) {

        / / 1. OkhttpClient object
        OkHttpClient okHttpClient = new OkHttpClient.Builder().
                // In this case, you can also set up data caching, etc
                // Set the timeout period
                connectTimeout(15, TimeUnit.SECONDS).
                readTimeout(20, TimeUnit.SECONDS).
                writeTimeout(20,  TimeUnit.SECONDS).
                addInterceptor(appInterceptor)./ / Application interceptors
                // Error reconnection
                retryOnConnectionFailure(true).
                build();

        / / 2 construction Request,
        //builder.get() represents a get request, and the url is a network address
        Request.Builder builder = new Request.Builder();

        Request request = builder.get().url(url).build();

        //3 Encapsulate Request as call
        Call call = okHttpClient.newCall(request);

        //4, execute call, which requests data asynchronously
        call.enqueue(callback);

    }

    public void post(String url, List<String> list, Callback callback, RequestBody requestBody) {

        / / 1. OkhttpClient object
        OkHttpClient okHttpClient = new OkHttpClient.Builder().
                // In this case, you can also set up data caching, etc
                // Set the timeout period
                connectTimeout(15, TimeUnit.SECONDS).
                addInterceptor(appInterceptor)./ / Application interceptors
                readTimeout(20, TimeUnit.SECONDS).
                writeTimeout(20,  TimeUnit.SECONDS).
                // Error reconnection
                retryOnConnectionFailure(true).
                build();

         RequestBody requestBodyPost = requestBody;

         Request requestPost = new Request.Builder()
         .url(url)
         .post(requestBodyPost)
         .build();

         okHttpClient.newCall(requestPost).enqueue(callback);

    }

    /** * Apply interceptor */
    Interceptor appInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();

            // -- Things to do before requesting ————

            Response response = chain.proceed(request);

            // -- do something after the request ————

            returnresponse; }}; }Copy the code

2. Android–OKHttpUtils framework package

OKHttpUtils: A web request framework focused on making web requests simpler, requiring only one line of code for any form of web request. It is a wrapper over OKHttp that is intended to make web requests easier.

Okhttp supports reconnection between HTTP2 and socket. Automatically selects the best route and has its own connection pool maintained by socket. It can reduce the number of TCP handshakes, and it has a pool of queue threads that can easily concurrent requests. (2) The unique network caching mode OKHttpUtils is not available in most network frameworks. For example, the network boss of our company requires not only to display network data when there is a network, but also to use cached data when there is no network. When we use normal network requests, we need a lot of judgment. Different data is saved according to whether the current state is on or off the network. Then decide whether to use caching. But this is a general notation. So OKHttpUtils uses automatic network caching mode. Let the user focus only on data processing. (3) Easy to use extension interface can add global public parameters, global interceptor, global timeout, and can be customized for a single request interceptor. Request parameter changes and so on. (4) powerful Cookie preservation strategy on the client side of the Cookie acquisition is not a particularly simple thing, Cookie automatic management, and provides additional Cookie management methods, the introduction of additional automatic management, add any cookies you want to create.

Dependency package import

compile 'com. Zhy: okhttputils: 2.0.0'

Copy the code

Make a GET request

    private String get(String url) throws IOException {

      Request request = new Request.Builder()

          .url(url)/ / url

          .build();/ / create

      // Pass request to client
      //execute() the execution thread
      Response response = client.newCall(request).execute();

      return response.body().string(a); }Copy the code

Make a POST request

    private String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

Copy the code

Request a single image using okhttp-utils

public void getImage(a)
        {
         tv_result.setText("");
            String url = "http://images.csdn.net/20150817/1.jpg";
            OkHttpUtils
                    .get()//
                    .url(url)//
                    .tag(this)//
                    .build()//
                    .connTimeOut(20000)// The link timed out
                    .readTimeOut(20000)// Read times out
                    .writeTimeOut(20000)// Write timeout
                    .execute(new BitmapCallback()
                    {
                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            tv_result.setText("onError:" + e.getMessage());
                        }

                        @Override
                        public void onResponse(Bitmap bitmap, int id)
                        {
                            Log.e("TAG"."OnResponse: complete"); iv_icon.setImageBitmap(bitmap); }}); }Copy the code

Upload multiple or single files using okhttp-utils

 /** * Upload multiple or single files using okhttp-utils */     
     public void multiFileUpload(a)
        {

         //FileUploadServlet
         String mBaseUrl = "http://192.168.3.27:8080/FileUpload/FileUploadServlet";

            File file = new File(Environment.getExternalStorageDirectory(), "tupian.jpg");
            File file2 = new File(Environment.getExternalStorageDirectory(), "zanghao.jpg");
            if(! file.exists()) { Toast.makeText(OKHttpActivity.this."File does not exist, please change file path", Toast.LENGTH_SHORT).show();
                return;
            }
// Map
      
        params = new HashMap
       
        ();
       ,>
      ,>
// params.put("username", "username");
// params.put("password", "123");

            String url = mBaseUrl;
            OkHttpUtils.post()//
                    .addFile("mFile"."server_tupian.jpg", file)//
                    .addFile("mFile"."server_zanghao.jpg", file2)// If you comment out one addFile, you can upload a single file
                    .url(url)
// .params(params)//
                    .build()//
                    .execute(new MyStringCallBack());/ / callback
        }

Copy the code

The callback processing

/** * for callback *@author Mloong
     *
     */
    private class MyStringCallBack extends StringCallback{

        @Override
        public void onBefore(Request request, int id) {
            // TODO Auto-generated method stub
            super.onBefore(request, id);

            setTitle("loading...");
        }

        @Override
        public void onAfter(int id) {
            // TODO Auto-generated method stub
            super.onAfter(id);

            setTitle("sample-okhttp");
        }

        / / error
        @Override
        public void onError(Call arg0, Exception e, int arg2) {

            e.printStackTrace();

            tv_result.setText("onError:"+e.getMessage());

        }

        // Callback on success
        @Override
        public void onResponse(String response, int id) {

            // Displays text information
            tv_result.setText("onResponse:"+ response);

            switch (id) {
            case 100:

                Toast.makeText(OKHttpActivity.this."http", Toast.LENGTH_LONG).show();

                break;

            case 101:

                Toast.makeText(OKHttpActivity.this."https", Toast.LENGTH_LONG).show();

                break;

            default:
                break; }}@Override
        public void inProgress(float progress, long total, int id) {

            Log.e(TAG, "inProgress:"+progress);

            mProgressBar.setProgress((int) (100*progress)); }}Copy the code

4. Download the project source code

Link: pan.baidu.com/s/1f3eZhmfK… Password: cv4b

About all the learning content of OKHTTP, we have a systematic knowledge system and advanced video materials, friends in need can add group for free android advanced video tutorial, source code, interview materials, there are cattle in the group together to discuss technology; (including custom controls, NDK, architecture design, React Native (Weex), performance optimization, complete commercial project development, etc.)

Android Advanced advanced video tutorial