Use and encapsulation of Android combat--OKHTTP3

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.