This article covers the following topics:
- What is OKHTTP3?
- Demo of the OKHTTP3 Tool class (package based on the Okhttp tool class)
- OKHTTP3 Packaging for Tool classes
Use the exact words of the author's project: HTTP and HTTP/2 clients for Android and Java applications
Its Project address: https://github.com/square/okhttp
1. Get request
2. Post request
3. File Upload
4. File download
Since the OKHTTP3 is dependent on the Okio for development, it is important to introduce the Okio as well. Old Clothes
We encapsulated the httputils based on the use of OKHTTP3, which is very simple to use, as is the case with third-party platform APIs.
Here, use Response.body (). String () to return the contents of the response result
OKHTTP3 is implemented using the constructor pattern, the following is a simple API introduction:
- Request.builder Request Constructor
- URL (String URL): Requested URL
- Post (): Default is Get mode
- Post (requestbody body): Post with parameters
- Build (): Construct request
There are three request parameters:
- Requestbody: Normal Request parameters
- Formbody.builder: A request parameter that passes a key-value pair as a form
- Multipartbody.builder: Request parameters for uploading a file as a form
Execution method:
- Pager
- Enqueue (Callback Callback): Asynchronous request
- Execute (): Sync request
Create the Httputils tool class, because OKHTTP3 does not recommend creating multiple objects, so a hungry man singleton mode is used
OKHTTP3 also provides synchronous request methods, which are used asynchronously to demonstrate the Call.execute () method.
If you need progress in the download file, you can modify the contents of the Onresponse callback to get the progress
Use and encapsulation of Android combat--OKHTTP3