Novate: Upgrade fit2.0 and RxJava are enhanced. novaterxjava

Source: Internet
Author: User

Novate: Upgrade fit2.0 and RxJava are enhanced. novaterxjava
Introduction

Novate Improvement

Optimized Design: adds basic APIs to reduce API redundancy powerful cache mode: supports offline caching, smart loading of cache without network, and allows you to configure whether cache cookie management is required: built-in cookie Management Mechanism all-round request mode: supports multiple methods to access the network (get, put, post, delete) and send to call: supports form, text, and json upload. File Transfer: Supports file download and upload, and dynamic addition of progress: supports adding request headers and parameters respectively. Result processing: supports unified processing of returned results and automatically serializes complex data. Strong Scalability: supports custom adaptive fit APIs. If the default APIs cannot meet the requirements, you can customize your own services. Convenient: supports Process Control for unified request networks, to help you perfectly add Processbar progress. RxJava: Combined with RxJava, thread intelligent control. Usage

Basic Construction:

 Novate novate = new Novate.Builder(this)            .baseUrl(baseUrl)            .build();

In addition to basic construction, other APIs are provided.

Build your header and parameter Map
 
  
Headers = new HashMap <> (); headers. put ("apikey", "4545sdsddfd7sds"); Map
  
   
Parameters = new HashMap <> (); parameters. put ("uid", "878787878 sdsd ");
  
 

Instantiation:

  Novate novate = new Novate.Builder(this)            .addParameters(parameters)            .connectTimeout(8)            .baseUrl("you api url")            .addHeader(headers)            .addLog(true)            .build(); 

More:

Novate = new Novate. builder (this ). addHeader (headers) // Add a public request header. addParameters (parameters) // public parameters. connectTimeout (10) // The connection time can be ignored. readTimeout (10) // read can be ignored. addCookie (false) // whether to synchronize cooike is not synchronized by default. addCache (true) // whether to cache the default cache. addCache (cache, cacheTime) // custom cache. baseUrl ("Url") // base URL. addLog (true) // whether to enable log. cookieManager (new NovateCookieManager () // custom cooike, which can be ignored. addInterceptor () // custom Interceptor. addNetworkInterceptor () // customize NetworkInterceptor. proxy (proxy) // sets proxy. client (client) // clent is not required by default. build ();

If you support https, you need to access the certificate:

      novate.addSSL(hosts,  certificates)

How to use it?

Prepare an array of certificate files and a host whitelist;

 int[] certificates = {R.raw.myssl1, R.raw.myssl2,......} int[] hosts = {"https:// you hosturl2", "https:// you hosturl2",......}

What else?

Certificates is the id of your ssl Certificate file. Put it under the raw resource file in the project,How to generate myssl. cer? use a pc browser to automatically export and save the certificate. If you are not clear about it, I will be drunk.

You do not want to cache an api:

 novate.addCache(false)

Do not want cookie persistence for an api:

 novate.addCookie(false)

A lot of people also want to ask me how to expand novate? Don't worry, Novate also provides the following methods:

 novate.addInterceptor() .addCallAdapterFactory() .callFactory() .proxy() .client()

The above just lists a few simple APIs, more of them are still using the method name of Retrofit, how to use Retrofit, and how to use Novate.

What Should RxJava do?

 observable.subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread());

Thread control has been implemented internally, and all requests are in the preceding thread format. You do not need to add them manually.

RxApi

The API that mainly processes requests,

Including RxGet, RxPost, RxDelete, RxPut, RxBody, RxFrom, RxUpLoad, RxDownLoad.

Before using basic APIs, read the introduction to RxCallBack.

RxGet

You can select multiple methods to return results. For details about how to return different data types, see RxCallBack.

Basic usage:

Returns String

 new Novate.Builder(this) .baseUrl("http://ip.taobao.com/") .build() .rxGet("service/getIpInfo.php", parameters, new RxStringCallback() { @Override public void onStart(Object tag) { super.onStart(tag); } @Override public void onNext(Object tag, String response) { } @Override public void onError(Object tag, Throwable e) { } @Override public void onCancel(Object tag, Throwable e) { } });

Return Bean

 novate.rxGet("path or url", parameters, new RxResultCallback  () { }); 

Return List

New Novate. Builder (this). baseUrl ("http://xxx.com/"). build (). rxGet ("service/getList", parameters, new RxListCallback  > () {@ Override public void onNext (Object tag, int code, String message, List  Response) {}@ Override public void onError (Object tag, Throwable e) {}@ Override public void onCancel (Object tag, Throwable e ){}}); 
   
  • Return File
 novate.rxGet("path or url", null, new RxFileCallBack(filePath, "name.jpg") { });
RxPost:

Post request call

Returns String

 novate.rxPost("path or url", parameters, new RxStringCallback() { });

Return Bean

 novate.rxPost("path or url", parameters, new RxResultCallback  () { }); 

Return List

 novate.rxPost("path or url", parameters, new RxListCallback  >() { .... }); 

Return File

 novate.rxPost("path or url", null, new RxFileCallBack(filePath, "name.jpg") { });
RxUpLoad

Post Data in the Body mode to report files, images, and multimedia files.

Novate provides two methods to upload files.Body and part ModesThe Body does not contain the key value, and the part contains the key value.

RxUploadWithBody

Post Data in the Body mode to report files and images.

 String mPath = uploadPath; //"you File path "; String url = "http:/xxx.com"; novate.rxUploadWithBody(url, new File(mPath), new RxStringCallback() { @Override public void onNext(Object tag, String response) { } @Override public void onError(Object tag, Throwable e) { } @Override public void onCancel(Object tag, Throwable e) { } });}
RxUploadWithPart

Upload files. The default key is* Image*

 String mPath = uploadPath; //"you File path "; String url = "http:/xxx.com"; File file = new File(mPath); novate.rxUploadWithPart(url, file, new RxStringCallback() { @Override public void onError(Object tag, Throwable e) { } @Override public void onCancel(Object tag, Throwable e) { } @Override public void onNext(Object tag, String response) { } });

For more information about custom keys, see the following.

String mPath = uploadPath; // "you File path"; String url = "http:/xxx.com"; File file = new File (mPath); RequestBody requestFile = RequestBody. create (MediaType. parse ("multipart/form-data; charset = UTF-8"), file); final NovateRequestBody requestBody = Utils. createNovateRequestBody (requestFile, new UpLoadCallback () {@ Override public void onProgress (Object tag, int progress, long speed, boolean done) {updateProgressDialog (progress) ;}}); MultipartBody. part body2 = MultipartBody. part. createFormData ("image", file. getName (), requestBody); // change the image to the key novate agreed with the server. rxUploadWithPart (url, body2, new RxStringCallback () {@ Override public void onError (Object tag, Throwable e) {}@ Override public void onCancel (Object tag, Throwable e) {}@ Override public void onNext (Object tag, String response ){}});
Upload multiple files: rxUploadWithPartListByFile:
 List  fileList = new ArrayList<>(); fileList.add(file); fileList.add(file); fileList.add(file); novate.rxUploadWithPartListByFile(url, fileList, new RxStringCallback() { @Override public void onStart(Object tag) { super.onStart(tag); } @Override public void onNext(Object tag, String response) { } @Override public void onError(Object tag, Throwable e) { } }) 
RxDownLoad

Download data in get mode. You can download files, images, and multimedia files.

Use rxGet () to download:
 String downUrl = "http://wap.dl.pinyin.sogou.com/wapdl/hole/201512/03/SogouInput_android_v7.11_sweb.apk"; novate.rxGet(downUrl, parameters, new RxFileCallBack(FileUtil.getBasePath(this), "test.apk") { @Override public void onStart(Object tag) { super.onStart(tag); showPressDialog(); } @Override public void onNext(Object tag, File file) { dismissProgressDialog(); } @Override public void onProgress(Object tag, float progress, long downloaded, long total) { updateProgressDialog((int) progress); } @Override public void onError(Object tag, Throwable e) { } @Override public void onCancel(Object tag, Throwable e) { } @Override public void onCompleted(Object tag) { super.onCompleted(tag); } });
RxDown () download
String downUrl =" http://wap.dl.pinyin.sogou.com/wapdl/hole/201512/03/SogouInput_android_v7.11_sweb.apk "; New Novate. builder (this ). baseUrl (baseUrl ). build (). rxDownload (downUrl, new RxFileCallBack () {@ Override public void onStart (Object tag) {super. onStart (tag); showPressDialog () ;}@ Override public void onNext (Object tag, File file) {dismissProgressDialog (); Toast. makeText (ExampleActivity. this, "Download successful! ", Toast. LENGTH_SHORT ). show () ;}@ Override public void onProgress (Object tag, float progress, long downloaded, long total) {updateProgressDialog (int) progress );} @ Override public void onProgress (Object tag, int progress, long speed, long transfered, long total) {super. onProgress (tag, progress, speed, transfered, total); updateProgressDialog (int) progress) ;}@ Override public void onError (Object tag, Throwable e) {}@ Override public void onCancel (Object tag, Throwable e) {}@ Override public void onCompleted (Object tag) {super. onCompleted (tag); dismissProgressDialog ();}});
Custom Api

By default, the above method will handle the built-inBaseApiService, if the defaultBaseApiServiceIf you cannot meet your needs, Novate also supports your own ApiService.

Define your own API:

MyAPI

 public interface MyAPI { @GET("url") Observable  getdata(@QueryMap Map  maps); }  

Execute Call

Provided by novateCreate () instantiate your API

 MyAPI myAPI = novate.create(MyAPI.class);

You don't need to worry about using novate. call () to execute your interface. The RxJava thread control has also been implemented in novate.

 novate.call(myAPI.getdata(parameters), new BaseSubscriber  (ExempleActivity.this) { @Override public void onError(Throwable e) { } @Override public void onNext(MyBean MyBean) { } });} 
Cancel

Each execution of novate. xxx () returns a subscribe to the upper layer. The upper layer can call unsubscribe () to cancel the operation!

 if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); }
Cancel

Each execution of novate. xxx () returns a subscribe to the upper layer. The upper layer can call unsubscribe () to cancel the operation!

Note:

This framework includes the following data:
{int code, String message(msg), T data(result)}

If the format of the data returned by your API is not the default format above, if you want to use native data, useRxStringCallback, orRxGenericsCallback, which solves the problem of incompatible data formats.

Thanks

I would like to thank all my friends who have provided ideas and tests for providing suggestions and ideas, so that I can continue to improve novate ,. Some people have read or read this framework and think it is very good. Therefore, they provide configurable solutions:

If you want to change the success callback process for returned data, a dynamic solution is also provided. The upper-layer callback can implement the required rxcallback in the following ways:

/*** The subclass can be rewritten without specifying its own validation rules for the backend data validation subclass by default */public boolean isReponseOk (Object tag, ResponseBody responseBody) {// whether the original data processing is deemed as successful ...... return your judgment ;}

If you think the service code and error code of this framework are too dead, the framework has already provided customized solutions. For example, you can modify the config file in Assets in your project:

If you want to use the default success status code: 0, the failure is not 0, you can ignore the following configuration files.


{
"IsFormat": "false ",
"SucessCode ":[
"1 ",
"0 ",
"1001"
],
"Error ":{
"1001": "network exception"
}
}

If you do not want to check the result formatting, set isFormat to: false.

If you need to modify the successful business of sucessCode, add your successful business code to the sucessCode node and refer to the above practices.

Error Code

You need to customize the translation of error codes. Please configure the error information, which can be configured:

'{"IsFormat": "false", "sucessCode": ["1", "0", "1001"], "error": {"1001 ": "network exception", "1002": "add your exception information "}}

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.