This article looks at okHttp, the most commonly used version of Android web requests
OkHttp is a lightweight web request framework contributed by Square.
GIthub address: OkHttp
Let’s start by learning how to use OkHttp
The preparatory work
/ / okHttp 3.14 implementation 'com. Squareup. Okhttp3: okHttp: 3.14.9'Copy the code
Add permissions
<uses-permission android: />
Copy the code
And now we can begin in earnest
There are two types of OkHttp requests: synchronous and asynchronous
Both GET and POST have synchronous and asynchronous modes
synchronous
-
Get the synchronization
The synchronization request of GET, the synchronization request is done in the child thread, and the UI update is done in the UI thread.
OkHttpClient okHttpClient = new OkHttpClient(); Request = new request.builder ().url(BASE_URL).build(); Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { Log.i(TAG, "getDataSync: " + response.body().string()); Handler.post (new Runnable() {@override public void run() {// update UI}}); } } catch (IOException e) { e.printStackTrace(); }Copy the code
The request is judged by the isSuccessful method of response and can be processed after success. If you’re doing something to the UI you need to do it in the main thread.
-
The post of synchronization
Post requests simply need to concatenate the POST () method after the Request instantiation, based on get.
The following is an asynchronous request.
asynchronous
The callback to an asynchronous request is in the child thread, and UI updates need to be done in the main thread.
- Get the asynchronous
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(BASE_URL).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Failure } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Log.i(TAG, "onResponse: " + response.body().string()); // Update UI}}});Copy the code
Ps: The enqueue() method for asynchronous requests automatically puts the request part into the worker thread for processing. The callback method is in the worker thread.
- Post asynchrony Post asynchrony is basically the same as GET asynchrony. As with the synchronization above, all you need to do is call POST in the Request build.
OkHttpClient client = new OkHttpClient(); // FormBody.builder Builder = new formBody.builder (); builder.add("args1", "values1"); Request post = new Request.Builder().url(BASE_URL).post(builder.build()).build(); client.newCall(post).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Failure } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { response.body().string(); // TODO } } });Copy the code
Note that when you call the post method, you pass in the RequestBody argument, which is of type RequestBody. This parameter can be divided into four cases.
- RequestBody type parameter
- FormBody object This object is used to pass parameters in the form of key-value pairs. The above POST asynchrony is through this object.
- RequestBody object This object is used to pass JSON or File
MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String jsonString = "{"name":"Alex","sex":"Male"}"; RequestBody = requestBody. create(JSON, jsonString);Copy the code
- MultipartBody object this object can pass parameters of a compound type.
MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("name", "Alex")
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("file/*"), file))
.build();
Copy the code
- Custom RequestBody object We can implement stream upload by inheriting RequestBody
That’s how OkHttp is used.
See OkHttp for basic usage