Basic usage of Android OkHttp

OkHttp can be said to be one of the most popular network request frameworks today. Today, let's explore the usage of OkHttp, including Get request, Post request, upload and download files, upload and download pictures and other functions

Before using OKHttp, you must first understand the following core classes:

  • OkHttpClient: client object
  • Request: access request, the Post request needs to contain the RequestBody
  • RequestBody: Request data, used in Post requests
  • Response: the response result of the network request
  • MediaType: data type, used to indicate that the data is a series of formats such as json, image, pdf, etc.
  • client.newCall(request).execute(): Synchronous request method
  • client.newCall(request).enqueue(Callback callBack): Asynchronous request method, but Callback is executed in the child thread, so UI update operation cannot be performed here

Before using it, you need to add the OkHttp dependency library to the project, and add the following statement to the gradle of the corresponding Module

compile 'com.squareup.okhttp3:okhttp:3.6.0'

In addition, OkHttp internally relies on another open source library OkIo, so it should also be imported

compile 'com.squareup.okio:okio:1.11.0'

Then synchronize the project and
OkHttp's GitHub address is: OkHttp
OkIo's GitHub address is: OkIo

1. Get request

The most common network request method can be said to be the Get request, here to get the webpage content of my personal homepage in Jianshu

public void get(View view) {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式,链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url("http://www.jianshu.com/u/9df45b87cfdf").build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(GetActivity.this, "Get 失败");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String responseStr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(responseStr);
                    }
                });
            }
        });
    }

It should be noted that the callback function of the asynchronous call is in the sub-thread, because Handler or runOnUiThread needs to be used to update
the UI. A Toast tool class is used here. The user determines whether the current thread is the main thread, and if so, the Toast will pop up directly. Otherwise, use runOnUiThread to pop up Toast

/**
 * 作者: 叶应是叶
 * 时间: 2017/4/2 15:41
 * 描述:
 */
public class ToastUtil {

    public static void showToast(final Activity activity, final String message) {
        if ("main".equals(Thread.currentThread().getName())) {
            Log.e("ToastUtil", "在主线程");
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("ToastUtil", "不在主线程");
                    Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}

Also, in the following method of the callback function

public void onResponse(Call call, final Response response)

If you want to get the returned string, you can use

response.body().string()

If you want a byte array, use

response.body().bytes()

If you want an input stream, use

response.body().byteStream()

2. Post type

When using the Post method in OkHttp to send a request body to the server, the request body needs to be a RequestBody. The request body can be:

  • key-value: key-value pair type
  • String: String type
  • Form: Html-like form data submission
  • Stream: Stream type
  • File: file type

3. Post key-value pair

 public void postParameter(View view) {
        OkHttpClient client = new OkHttpClient();
        //构建FormBody,传入要提交的参数
        FormBody formBody = new FormBody
                .Builder()
                .add("username", "initObject")
                .add("password", "initObject")
                .build();
        final Request request = new Request.Builder()
                .url("http://www.jianshu.com/")
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(PostParameterActivity.this, "Post Parameter 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                ToastUtil.showToast(PostParameterActivity.this, "Code:" + String.valueOf(response.code()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(responseStr);
                    }
                });
            }
        });
    }

Here, two parameter values ​​are submitted to the homepage of Jianshu's website, and the function of simulating login can be realized through Post. Of course, this only simulates the Post operation. After submitting the parameters, it will jump to the 404 page
at

public void onResponse(Call call, Response response)

through the method

response.code()

The result code of integer type can be obtained: 404

4. Post string

In the above example, Post passes parameter pairs. Sometimes we need to transmit strings, such as sending a JSON string to the server. Then you can use the following method:

public void postString(View view) {
        OkHttpClient client = new OkHttpClient();
        //RequestBody中的MediaType指定为纯文本,编码方式是utf-8
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),
                "{username:admin;password:admin}");
        final Request request = new Request.Builder()
                .url("http://www.jianshu.com/")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(PostStringActivity.this, "Post String 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                ToastUtil.showToast(PostStringActivity.this, "Code:" + String.valueOf(response.code()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(responseStr);
                    }
                });
            }
        });
    }

5. Post form

By viewing the Html source code of the website login page, you can usually view the login form in the following format

<form id="fm1" action="" method="post">
    <input id="username" name="username" type="text"/>    
    <input id="password" name="password" type="password"/>                    
</form>

Here, MuiltipartBody is used to build a RequestBody, which is a subclass of RequestBody. This class is used to submit form data.

public void postForm(View view) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "叶应是叶")
                .addFormDataPart("password", "叶应是叶")
                .build();
        final Request request = new Request.Builder()
                .url("http://www.jianshu.com/")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(PostFormActivity.this, "Post Form 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                ToastUtil.showToast(PostFormActivity.this, "Code:" + String.valueOf(response.code()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(responseStr);
                    }
                });
            }
        });
    }

6. Post stream

public void postStreaming(View view) {
        final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MEDIA_TYPE_MARKDOWN;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("Numbers\n");
                sink.writeUtf8("-------\n");
                for (int i = 2; i <= 997; i++) {
                    sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
                }
            }

            private String factor(int n) {
                for (int i = 2; i < n; i++) {
                    int x = n / i;
                    if (x * i == n) return factor(x) + " × " + i;
                }
                return Integer.toString(n);
            }
        };
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(PostStreamingActivity.this, "Post Streaming 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                ToastUtil.showToast(PostStreamingActivity.this, "Code:" + String.valueOf(response.code()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(responseStr);
                    }
                });
            }
        });
    }

7. Post file

public void postFile(View view) {
        OkHttpClient client = new OkHttpClient();
        final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        File file = new File("README.md");
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(PostFileActivity.this, "Post File 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                ToastUtil.showToast(PostFileActivity.this, "Code:" + String.valueOf(response.code()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(responseStr);
                    }
                });
            }
        });
    }

8. Download pictures

public void downImage(View view) {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request
                .Builder()
                .get()
                .url("http://avatar.csdn.net/B/0/1/1_new_one_object.jpg")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(DownImageActivity.this, "下载图片失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                //将图片显示到ImageView中
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv_result.setImageBitmap(bitmap);
                    }
                });
                //将图片保存到本地存储卡中
                File file = new File(Environment.getExternalStorageDirectory(), "image.png");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                byte[] temp = new byte[128];
                int length;
                while ((length = inputStream.read(temp)) != -1) {
                    fileOutputStream.write(temp, 0, length);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                inputStream.close();
            }
        });
    }

After specifying the image address and downloading successfully, obtain the input stream of the image, first Bitmap decodeStream(InputStream is)convert the input stream to Bitmap and display it, and then save the image to the root directory of the local memory card.
Remember to apply for the write permission of the memory card.

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

Nine, parsing Json

Here, the content of the response is parsed into Java Bean through Gson.
First, you need to import the Gson.jar file into the project

Here, let's access the interface " http://news-at.zhihu.com/api/4/themes " through OkHttp , get Json data and parse it into JavaBean entities

write picture description here

First create a JavaBean based on the Json format

/**
 * 作者: 叶应是叶
 * 时间: 2017/4/2 22:27
 * 描述:
 */
public class Bean {

    private String date;

    private List<StoriesBean> stories;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public List<StoriesBean> getStories() {
        return stories;
    }

    public void setStories(List<StoriesBean> stories) {
        this.stories = stories;
    }

    public static class StoriesBean {

        private int type;

        private int id;

        private String ga_prefix;

        private String title;

        private boolean multipic;

        private List<String> images;

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getGa_prefix() {
            return ga_prefix;
        }

        public void setGa_prefix(String ga_prefix) {
            this.ga_prefix = ga_prefix;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public boolean isMultipic() {
            return multipic;
        }

        public void setMultipic(boolean multipic) {
            this.multipic = multipic;
        }

        public List<String> getImages() {
            return images;
        }

        public void setImages(List<String> images) {
            this.images = images;
        }

        @Override
        public String toString() {
            return "标题='" + title + '\'' + "图片链接=" + images;
        }
    }

}

Get Json data and parse it

public void parseJson(View view) {
        OkHttpClient client = new OkHttpClient();
        final Gson gson = new Gson();
        Request request = new Request.Builder()
                .url("http://news-at.zhihu.com/api/4/news/before/20131119")
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast(ParseJsonActivity.this, "parse Json 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ToastUtil.showToast(ParseJsonActivity.this, "Code:" + String.valueOf(response.code()));
                final Bean bean = gson.fromJson(response.body().charStream(), Bean.class);
                List<Bean.StoriesBean> stories = bean.getStories();
                final StringBuilder stringBuilder = new StringBuilder();
                for (Bean.StoriesBean storiesBean : stories) {
                    stringBuilder.append(storiesBean);
                    stringBuilder.append("\n\n\n");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_result.setText(stringBuilder.toString());
                    }
                });
            }
        });
    }

Parsing result:


write picture description here


Author: Ye Yingshiye
Link : https://www.jianshu.com/p/c478d7a20d03
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778245&siteId=291194637