A standard RESTful style networking framework based on okhttp

A standard RESTful style networking framework based on okhttp

2022-09-16 0 1,070
Resource Number 38596 Last Updated 2025-02-24
¥ 0USD 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/kyym/a-standard-restful-style-networking-framework-based-on-okhttp.html

Share free open-source source code

Q&A
  • 1, automatic: after taking the photo, click the (download) link to download; 2. Manual: After taking the photo, contact the seller to issue it or contact the official to find the developer to ship.
View details
  • 1, the default transaction cycle of the source code: manual delivery of goods for 1-3 days, and the user payment amount will enter the platform guarantee until the completion of the transaction or 3-7 days can be issued, in case of disputes indefinitely extend the collection amount until the dispute is resolved or refunded!
View details
  • 1. Heptalon will permanently archive the process of trading between the two parties and the snapshots of the traded goods to ensure that the transaction is true, effective and safe! 2, Seven PAWS can not guarantee such as "permanent package update", "permanent technical support" and other similar transactions after the merchant commitment, please identify the buyer; 3, in the source code at the same time there is a website demonstration and picture demonstration, and the site is inconsistent with the diagram, the default according to the diagram as the dispute evaluation basis (except for special statements or agreement); 4, in the absence of "no legitimate basis for refund", the commodity written "once sold, no support for refund" and other similar statements, shall be deemed invalid; 5, before the shooting, the transaction content agreed by the two parties on QQ can also be the basis for dispute judgment (agreement and description of the conflict, the agreement shall prevail); 6, because the chat record can be used as the basis for dispute judgment, so when the two sides contact, only communicate with the other party on the QQ and mobile phone number left on the systemhere, in case the other party does not recognize self-commitment. 7, although the probability of disputes is very small, but be sure to retain such important information as chat records, mobile phone messages, etc., in case of disputes, it is convenient for seven PAWS to intervene in rapid processing.
View details
  • 1. As a third-party intermediary platform, Qichou protects the security of the transaction and the rights and interests of both buyers and sellers according to the transaction contract (commodity description, content agreed before the transaction); 2, non-platform online trading projects, any consequences have nothing to do with mutual site; No matter the seller for any reason to require offline transactions, please contact the management report.
View details

Related Article

make a comment
No comments available at the moment
Official customer service team

To solve your worries - 24 hours online professional service