A standard RESTful style networking framework based on okhttp

A standard RESTful style networking framework based on okhttp

2022-09-16 0 1,436
Resource Number 38596 Last Updated 2025-02-24
¥ 0HKD Upgrade VIP
Download Now Matters needing attention
Can't download? Please contact customer service to submit a link error!
Value-added Service: Installation Guide Environment Configuration Secondary Development Template Modification Source Code Installation

This issue recommends a standard RESTful style network framework based on okhttp – OkGo-3.0.

A standard RESTful style networking framework based on okhttp插图

OkGo 3.0 is based on Http protocol and encapsulates OkHttp’s network request framework. It is simpler and easier to use than Retrofit, supports RxJava, RxJava2, and supports custom cache. Supports batch breakpoint download management and batch upload management.

Main functions

  • Basic get, post, put, delete, head, options, trace, patch eight kinds of requests
  • Support upString, upJson, upBytes, upFile and other up class methods to upload specific data
  • Supports uploading a file with one key, or uploading multiple files with one key, or uploading multiple files and multiple parameters together
  • Large file download and download progress callback
  • Large file upload and upload progress callback
  • Supports automatic cookie management, and can customize cookie management policy
  • Supports caching mode, not only supports http caching protocol, but also supports custom caching policies
  • Support redirection
  • Support for user-defined timeout automatic reconnection times
  • Support for chain calls
  • Support https access, support two-way authentication
  • Support cancellation requests based on tag, or cancel all
  • Support custom Callback, automatically parse network data

Dependence

//  must be used
compile 'com.lzy.net:okgo:3.0.4'

// Add the following three options, okrx and okrx2 cannot use  at the same time
compile 'com.lzy.net:okrx:1.0.2'
compile 'com.lzy.net:okrx2:2.0.2'
The compile < span class = "HLJS - string" > 'com.lzy.net: okserver: at 2.0.5' < / span > < / code > < / pre >

Example

1 Initial configuration

 

OkGo.getInstance().init(this); 

2 Available parameters

  • .post(url) : post request, of course, a total of support for GET, HEAD, OPTIONS, POST, PUT, DELETE, PATCH, TRACE these 8 request methods.
  • .params() : When adding parameters, the last isReplace parameter is optional and defaults to true, that is, if it represents the same key, the later one will override the previous one.
  • .tag(this) : tag of the request, which identifies the current request and facilitates subsequent cancellation of the corresponding request. If you do not need to cancel the request, you do not need to set this parameter.
  • .isMultipart() : This method indicates whether to force the use of multipart/form-data form upload, because when the framework has files, regardless of whether you set this parameter, the default is multipart/form-data format upload, but if the parameter does not contain files, The default upload format is application/x-www-form-urlencoded. Set this parameter to true if your server requires form uploads regardless of whether there are files.
  • .issplicEURl () : This method indicates whether to force params parameters to be concatenated after the url. The default false is not concatenated. In general, post, put and other methods with request bodies should put the parameters in the request body, should not be placed on the url, but some servers may not be standardized, url and request body need to pass parameters, so this time use the parameter, he will use all the parameters passed by the.params() method. Automatically concatenated after the url.
  • .retrycount () : This method is to configure the number of timeout reconnection, can also be set when the global initialization, the default use of global configuration, that is, 3 times, you can also here for your request a special configuration, will not affect the global other requests timeout reconnection times.
  • .cacheKey().cacheTime().cacheMode() : These three are cache-related configurations, see caching introduction
  • .headers() : This method is to pass the request header required by the server. If you do not know what a request header is, see the first page of the wiki about the http protocol link in network packet capture.
  • .params() : This method passes key-value pair parameters in the same format as the http protocol. For details, see the http protocol connection above.
  • .addurLParams ().addFileParams().addFileWrapperParams() : Here is support for a key to pass multiple text parameters, also supports a key to pass multiple file parameters, see the http protocol connection above for details.

3 Response object

There are five fields inside the Response object, which represent the following meanings:

  • body: the current returned data, T is the generic type of the data. Use the method body() to get the value. If the request is successful, call back onSuccess(), which is the data returned after convertResponse() parses the data. If an exception occurs, call onError(), which has a null value.
  • throwable: callback onError() if an exception occurs. This field holds the current exception information. If the request is successful, call back onSuccess() and the field is null. Use method getException() to get the value.
  • isFromCache: indicates where the current data comes from, true: from the cache, false: from the network. Use the method isFromCache() to get this value.
  • rawCall: represents the true okhttp3.Call object for the current request. Use the method getRawCall() to get the value.
  • rawResponse: indicates the okhttp3.Response object really returned by the server of the current request. Note: If the data comes from the cache, the object is null; if it comes from the network, the object has a value. Get the value using the method getRawResponse().

In addition, the object has the following methods:

  • code() : indicates the http response status code. If the data comes from the network, the value is the real response code regardless of the success or failure. If the data comes from the cache, the value is always -1.
  • message() : indicates the description of the http response status code. If the data comes from the network, the value is true regardless of the success or failure. If the data comes from the cache, the value is always null.
  • headers() : indicates the response header returned by the server. If the data is from the network, this value is true regardless of success or failure. If the data is from the cache, this value is always null.
  • isSuccessful() : Whether the request is successful depends on whether an exception occurs.

3 Example code

// Login request 
  String path = "https://......" ; // Login link 

OkGo.<String>post(path).tag(this)
                    .params("userName",userName)
                    .params("password",password)
                  .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            // Login success 
                        }

                        @Override
                        public void onError(Response<String> response) {
                            //Login failed 
                        }
                    });

Demo

A standard RESTful style networking framework based on okhttp插图1

A standard RESTful style networking framework based on okhttp插图2

A standard RESTful style networking framework based on okhttp插图3

A standard RESTful style networking framework based on okhttp插图4

—END—

Open Source protocol: Apache2.0

资源下载此资源为免费资源立即下载
Telegram:@John_Software

Disclaimer: This article is published by a third party and represents the views of the author only and has nothing to do with this website. This site does not make any guarantee or commitment to the authenticity, completeness and timeliness of this article and all or part of its content, please readers for reference only, and please verify the relevant content. The publication or republication of articles by this website for the purpose of conveying more information does not mean that it endorses its views or confirms its description, nor does it mean that this website is responsible for its authenticity.

Ictcoder Free Source Code A standard RESTful style networking framework based on okhttp https://ictcoder.com/a-standard-restful-style-networking-framework-based-on-okhttp/

Share free open-source source code

Q&A
  • 1. Automatic: After making an online payment, click the (Download) link to download the source code; 2. Manual: Contact the seller or the official to check if the template is consistent. Then, place an order and make payment online. The seller ships the goods, and both parties inspect and confirm that there are no issues. ICTcoder will then settle the payment for the seller. Note: Please ensure to place your order and make payment through ICTcoder. If you do not place your order and make payment through ICTcoder, and the seller sends fake source code or encounters any issues, ICTcoder will not assist in resolving them, nor can we guarantee your funds!
View details
  • 1. Default transaction cycle for source code: The seller manually ships the goods within 1-3 days. The amount paid by the user will be held in escrow by ICTcoder until 7 days after the transaction is completed and both parties confirm that there are no issues. ICTcoder will then settle with the seller. In case of any disputes, ICTcoder will have staff to assist in handling until the dispute is resolved or a refund is made! If the buyer places an order and makes payment not through ICTcoder, any issues and disputes have nothing to do with ICTcoder, and ICTcoder will not be responsible for any liabilities!
View details
  • 1. ICTcoder will permanently archive the transaction process between both parties and snapshots of the traded goods to ensure the authenticity, validity, and security of the transaction! 2. ICTcoder cannot guarantee services such as "permanent package updates" and "permanent technical support" after the merchant's commitment. Buyers are advised to identify these services on their own. If necessary, they can contact ICTcoder for assistance; 3. When both website demonstration and image demonstration exist in the source code, and the text descriptions of the website and images are inconsistent, the text description of the image shall prevail as the basis for dispute resolution (excluding special statements or agreements); 4. If there is no statement such as "no legal basis for refund" or similar content, any indication on the product that "once sold, no refunds will be supported" or other similar declarations shall be deemed invalid; 5. Before the buyer places an order and makes payment, the transaction details agreed upon by both parties via WhatsApp or email can also serve as the basis for dispute resolution (in case of any inconsistency between the agreement and the description of the conflict, the agreement shall prevail); 6. Since chat records and email records can serve as the basis for dispute resolution, both parties should only communicate with each other through the contact information left on the system when contacting each other, in order to prevent the other party from denying their own commitments. 7. Although the probability of disputes is low, it is essential to retain important information such as chat records, text messages, and email records, in case a dispute arises, so that ICTcoder can intervene quickly.
View details
  • 1. As a third-party intermediary platform, ICTcoder solely protects transaction security and the rights and interests of both buyers and sellers based on the transaction contract (product description, agreed content before the transaction); 2. For online trading projects not on the ICTcoder platform, any consequences are unrelated to this platform; regardless of the reason why the seller requests an offline transaction, please contact the administrator to report.
View details

Related Source code

ICTcoder Customer Service

24-hour online professional services