Network data reading framework - use of OkHttp

Introduction and usage of OkHttp framework

  • effect
    OkHttp is mainly used for network reading and file upload of data such as String, but it is not good enough in image cache processing, so you need to manually set the cache area

  • Use [take Android Studio for example]

1, Add OkHttp framework
In Android Studio, File → Project Structure → find the corresponding Module project → Denpendencies → click the plus sign → Library Dependency → enter the name of the frame you need. Here you need to add two frames:

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

2, To create an OkHttpClient object, you need to send a network request through the object [two methods]
1. No cache creation method

private OkHttpClient client = new OkHttpClient();

2. Cache creation mode

private OkHttpClient client;
//If you need to manually set or modify the cache processing, that is, timeout processing, use the following methods: set the cache and timeout processing through the builder object
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//Set connection timeout, currently 10 hours
builder.connectTimeout(10, TimeUnit.HOURS);
//Set read time-out
builder.readTimeout(10, TimeUnit.HOURS);
//Set write data, upload data timeout
builder.writeTimeout(10, TimeUnit.HOURS);
//Set cache information processing: create a cache object, and the construction method is used to control the cache location and maximum cache size [unit: Byte]
Cache cache = new Cache(new File("/mnt/sdcard/usher"), 10 * 1024 * 1024);
builder.cache(cache);
//Initializing the OkHttp object through the builder object
client = builder.build();

3, Processing methods of network data
1. GET request mode 1

    *step
    * 1,encapsulation Request Object to set the requested URL and the requested conditions
    * 2,By initializing Builder Object to set some network request information[ url Web address used to set up the connection]
    * 3,adopt Builder After setting the relevant information, you only need to pass the build The corresponding Request object
    * */
        String url = "http://bz.budejie.com/?typeid=2&ver=3.4.3&no_cry=1&client=android&c=wallPaper&a=category";
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);//Get the Call object of this request task
        //Execute request
        call.enqueue(new Callback() {
            @Override//Method of request send failure call
            public void onFailure(Call call, IOException e) {
                Log.i("==", "onFailure: Data acquisition failed");
            }

            @Override//Request to send the method of successful call: this method runs in the sub thread. If you want to update the page through the result, you need to pass the result to the main thread through Hanlder
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("==", "The result of this request is:" + result);
                Log.i("==", "onResponse method:" + Thread.currentThread().getName());
                Log.i("==", "Location of cache  " + client.cache().directory().getAbsolutePath());
                Log.i("==", "Used size of cache  " + client.cache().size());
                Log.i("==", "Maximum size of cache  " + client.cache().maxSize());
                //Please create the Handler object yourself in the onCreate method
                Message message = Message.obtain();
                message.what = 1;
                message.obj = result;
                handler.sendMessage(message);
            }
        });

2. GET request mode 2

final Call call = client.newCall(
                new Request.Builder()
                        .url("http://bz.budejie.com/?typeid=2&ver=3.4.3&no_cry=1&client=android&c=wallPaper&a=category")
                        .build()
        );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    Log.i("==", "run: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

3. POST request mode

        //Encapsulation of request conditions through the create method of RequestBody
        RequestBody body = RequestBody.create(
                //Parameter 1: data type
                MediaType.parse("application/json; charset=utf-8"),
                //Parameter 2: request condition
                "platform=2&gifttype=1&compare=60841c5b7c69a1bbb3f06536ed685a48"
        );
        //Encapsulate request object
        final Request request = new Request.Builder()
                .url("http://zhushou.72g.com/app/gift/gift_list/")
                .post(body)
                .build();

        final Call call = client.newCall(request);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    Log.i("==", "run: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

4. File upload

File file = new File("/storage/emulated/0/DCIM/Screenshots/iPhone.png");//Create a file object
        RequestBody body = RequestBody.create(
                MediaType.parse("text/x-markdown; charset=utf-8"),
                file
        );
        final Call call = client.newCall(new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(body)
                .build()
        );
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    Log.i("", "run: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

4, Cancel OkHttp network access

//Just put theCallObject call cancel()Method
call.cancel();

Conclusion: OkHttp is mainly used to process text type data, but because it needs to set the cache manually, it has little advantage in obtaining image and other types of data.

PS: This is the first time I use Markdown to write an article. It's very comfortable and easy to use. It's highly recommended that you do copywriting or products and use them by fellow programmers

Another: welcome to my channel B: Lollipop, Guy's channel B
Content: technology + music

Tags: OkHttp network Android JSON

Posted on Tue, 26 May 2020 11:29:46 -0400 by ayok