Full Analysis of OkHttp3 Usage

Keywords: Android network github Gradle

1. Prepare before use

Android Studio configuration gradle:

 compile 'com.squareup.okhttp3:okhttp:3.2.0'
  compile 'com.squareup.okio:okio:1.7.0'

Add network privileges:

<uses-permission android:name="android.permission.INTERNET"/>

2. Asynchronous GET requests

    private void getAsynHttp() {
    mOkHttpClient=new OkHttpClient();
    Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com");
    //Can be omitted, default is GET request
    requestBuilder.method("GET",null);
    Request request = requestBuilder.build();
    Call mcall= mOkHttpClient.newCall(request);
    mcall.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (null != response.cacheResponse()) {
                String str = response.cacheResponse().toString();
                Log.i("wangshu", "cache---" + str);
            } else {
                response.body().string();
                String str = response.networkResponse().toString();
                Log.i("wangshu", "network---" + str);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Request successful", Toast.LENGTH_SHORT).show();
                }
            });
        }
    });
}

2. Asynchronous POST requests

The difference between OkHttp3 asynchronous POST requests and OkHttp2.x is that there is no FormEncoding Builder class, instead of a more powerful FormBody:

  private void postAsynHttp() {
        mOkHttpClient=new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("size", "10")
                .build();
        Request request = new Request.Builder()
                .url("http://api.1-blog.com/biz/bizserver/article/list.do")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.i("wangshu", str);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Request successful", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        });
    }

3. Asynchronous upload of files

The upload file itself is also a POST request, which was not mentioned in the previous article. Here we add it. First, define the upload file type:

public static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

Upload the wangshu.txt file of the sdcard root directory to the server:

private void postAsynFile() {
    mOkHttpClient=new OkHttpClient();
    File file = new File("/sdcard/wangshu.txt");
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("wangshu",response.body().string());
            }
        });
    }

Of course, if you want to change to a synchronous upload file, just call mOkHttpClient.newCall(request).execute().
In the wangshu.txt file, there is a line: "Android network programming (6) OkHttp3 usage full parsing." We run the program and click the send file button. The final result of requesting the network to return is the content of our TXT file:

Here's a picture description.

Of course, don't forget to add the following permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

4. Asynchronous downloading of files

The download file is also not mentioned in the previous article. It's relatively simple to implement. Download a picture here. We can write the stream into the image file we specified after we get the Response.

private void downAsynFile() {
    mOkHttpClient = new OkHttpClient();
    String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
    Request request = new Request.Builder().url(url).build();
    mOkHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) {
            InputStream inputStream = response.body().byteStream();
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(new File("/sdcard/wangshu.jpg"));
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                }
                fileOutputStream.flush();
            } catch (IOException e) {
                Log.i("wangshu", "IOException");
                e.printStackTrace();
           }

           Log.d("wangshu", "File Download Successful");
       }
   });

}

5. Asynchronous upload of Multipart files

This scenario is very common. Sometimes we upload files and need to upload other types of fields. OkHttp3 is very simple to implement. It is important to note that no server receives my Multipart file. So here is just an example. The specific application should be combined with the corresponding server in the actual work.
First, define the upload file type:

   private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private void sendMultipart(){
    mOkHttpClient = new OkHttpClient();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("title", "wangshu")
            .addFormDataPart("image", "wangshu.jpg",
                    RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + "...")
            .url("https://api.imgur.com/3/image")
            .post(requestBody)
            .build();

   mOkHttpClient.newCall(request).enqueue(new Callback() {
       @Override
       public void onFailure(Call call, IOException e) {

       }

       @Override
       public void onResponse(Call call, Response response) throws IOException {
           Log.i("wangshu", response.body().string());
       }
   });
}

6. Setting timeout and caching

The difference between OkHttpClient and OkHttp2.x is that we can't set the timeout and cache directly through OkHttpClient, but through OkHttpClient.Builder. After OkHttpClient is configured by builder, we return OkHttpClient with builder.build(), so we don't usually call new OkHttpClient() to get OkHttpClient, but through builder.build():

    File sdcache = getExternalCacheDir();
    int cacheSize = 10 * 1024 * 1024;
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
    OkHttpClient mOkHttpClient=builder.build();            

7. About Canceling Requests and Encapsulation

OkHttpFinal, which is currently based on OkHttp3 for packaging. Link description

8. About Demo of Source Code

github source download Link description

Posted by vitch2002 on Sun, 14 Apr 2019 23:54:32 -0700