Http request generation started 30 seconds artifact RxHttp

Appetizer
did not talk much, 30s countdown begin, take a look at how to send a Get request, as follows:

RxHttp.get("http://...")  //第一步,确定请求类型,这里为Get请求           
    .asString()           //第二步,确定返回类型,这里返回String类型      
    .subscribe(s -> {     //第二步,订阅观察者,第二步返回Observable对象
        //请求成功                                         
    }, throwable -> {                                  
        //请求失败                                         
    });                                                

Ok, countdown! ! ! With this, you have learned the essence of RxHttp.
Yes, no doubt, is so simple to use RxHttp, any request, any return data type, follow these three steps, we call request trilogy.

The important thing to say three times
any request, any return data type, are to follow the request trilogy

Arbitrary request, any return data types are to follow the request Trilogy

Arbitrary request, any return data types are to follow the request Trilogy


gradle dependence

implementation 'com.rxjava.rxhttp:rxhttp:1.0.8'
//注解处理器,生成RxHttp类,即可一条链发送请求
annotationProcessor 'com.rxjava.rxhttp:rxhttp-compiler:1.0.8'

Note: RxHttp class is automatically generated by the annotation processor, it requires you to use an annotation in the project, and then rebuild it projects, RxHttp which can generate.

Trilogy Commentary

I believe many people here have doubts

  • If I want to send in other ways such as Post request it?
  • File upload and download monitor the progress of it?
  • I want to get custom data type it?

How they achieve it through the trilogy? Do not worry, followed by one for you on the
first step, to determine the manner requested
the example above, we call RxHttp.get ( " HTTP: // ...") statement, which the operator will get the code Get request. Thus, we can guess, send Post requests only need to call the operator to post. However, we only got it half, why do you say that? Post request, we commonly divided into two types, one form of Post form, and the other is Json string of Post. For this purpose, RxHttp operator provides two transmission Post request, and are postForm postJosn, at this time, we can send this request Post

RxHttp.postForm("http://...")  //发送表单形式的Post请求           
    .asString()                //返回String类型      
    .subscribe(s -> {          //订阅观察者,
        //请求成功                                         
    }, throwable -> {                                  
        //请求失败                                         
    });  

RxHttp.postJson("http://...")  //发送Json字符串单形式的Post请求           
    .asString()                //返回String类型      
    .subscribe(s -> {          //订阅观察者,
        //请求成功                                         
    }, throwable -> {                                  
        //请求失败                                         
    });    

If you want to send the request otherwise Delete, Put, etc. Similarly, as follows:

RxHttp.deleteForm("http://...")
RxHttp.deleteJson("http://...")
RxHttp.putForm("http://...")
RxHttp.putJson("http://...")
//其它请求方式同上

Finally, we look at, we RxHttp offer a way which requests, as follows:
Http request generation started 30 seconds artifact RxHttp

Which get, postForm, postJson already mentioned above, the other the same token, there is no longer tells the story.
Request a way to determine how to add parameters or picture message? so easy !!!, simply call add, addHeader to, the following:

RxHttp.postForm("http://...")  //发送表单形式的Post请求     
    .add("key","value")        //添加请求参数,该方法可调用多次                 
    .addHeader("headerKey","headerValue")  //添加请求头参数,该方法可调用多次 
    .asString()                //返回String类型      
    .subscribe(s -> {          //订阅观察者,
        //请求成功                                         
    }, throwable -> {                                  
        //请求失败                                         
    }); 

A second step of determining the return data type
above asString operator representative of return string type String, RxHttp provided asXXX operator 17, as follows:
Http request generation started 30 seconds artifact RxHttp
wherein, asBoolean, asInteger, asLong, asString like, I want to be well understood, is the return basic types of packing type, this is not too much to explain. Here we focus on the look asObject, asList, asDownload these three operators.
asObject
display development, we return more custom data types, such as a Student object we want this case, we can use asObject operator, as follows:

RxHttp.get("http://...")       //发送Get请求         
    .asObject(Student.class)   //指定返回User类型数据 
    .subscribe(student -> {    //订阅观察者,
        //请求成功,这里student就是Student对象                                         
    }, throwable -> {                                  
        //请求失败                                         
    });  

asList
However, if we want to get a series of Student objects? Use asObject obviously does not work, then we must use asList the operator, as follows:

RxHttp.get("http://...")        //发送Get请求         
    .asList(Student.class)      //指定返回User类型数据 
    .subscribe(students -> {    //订阅观察者,
        //请求成功,这里students就是List<Student>对象                                         
    }, throwable -> {                                  
        //请求失败                                         
    });  

NOTE: asXXX operator specified default internal execution request Schedulers.io () thread

asDownload
when we need to download the file, use this operator, as follows:

 RxHttp.get("http://...")        //Get请求                         
     .asDownload(".../rxhttp.apk")  //使用asDownload操作符,并传入存储路径
     .subscribe(s -> {                                       
         //下载成功回调,s为文件存储路径                                   
     }, (OnError) throwable -> {                             
         //下载失败回调                                            
     });                                                     

第三步,订阅观察者
在上一步中,细心的你也许发现了,使用了asXXX操作符后,会返回一个Observable对象,那这个又是什么对象呢?其实它就是RxJava内部的Observable对象。
在这,可以告诉你,当我们调用asXXX操作符,拿到Observable对象后,RxHttp就已经完成了它的使命,接下来的事情都丢给了RxJava。拿到Observable对象,结合RxJava强大的操作符,我们可以做非常多的事情,比如我们想要在主线程回调观察者,如下:

RxHttp.get("http://...")        //发送Get请求         
    .asList(Student.class)      //指定返回User类型数据 
    .observeOn(AndroidSchedulers.mainThread())  //主线程回调观察者
    .subscribe(students -> {    //订阅观察者,
        //请求成功,这里students就是List<Student>对象                                         
    }, throwable -> {                                  
        //请求失败                                         
    });  

注:请求默认在Schedulers.io()线程执行,如未指定观察者所在线程,则默认在请求所在线程回调

小结

好了,请求三部曲就讲解结束,到这,你已经掌握了RxHttp 70% 的功能,并且掌握了RxHttp的精髓----请求三部曲,在任意请求中,就能做到以不变应万变。 本篇文章的目的在于提供一个简单的入门教程,更多功能请查看后续

问题简答

最后,借此机会,简单解答一下读者反馈的问题
1、RxHttp支持Https吗?
答:支持,RxHttp内置默认的OkHttpClient对象,如下:

new OkHttpClient.Builder()                                    
    .connectTimeout(10, TimeUnit.SECONDS)                     
    .readTimeout(10, TimeUnit.SECONDS)                        
    .writeTimeout(10, TimeUnit.SECONDS)                       
    .sslSocketFactory(sslSocketFactory, trustAllCert) //添加信任证书
    .hostnameVerifier((hostname, session) -> true) //忽略host验证 
    .build();                                                 

2, RxHttp supports caching handle it?
Answer: Yes, but RxHttp default does not do any caching, if necessary, customize OkHttpClient objects open the cache, and sends a request using RxHttp when using cacheControl (CacheControl cacheControl) caching policies
3, RxHttp how to support session or token?
A: session token or to design specific business logic, it does not do RxHttp temporary package depth. If necessary, can be customized to achieve the object OkHttpClient via the interceptor.
4, RxHttp support kotlin it?
A: must support, but when dependent annotation processor is required instead of kapt AnnotationProcessor
5, how RxHttp support multi-task list download
A: In the latest Demo, the existing case, please download Demo Experience

Guess you like

Origin blog.51cto.com/14295695/2406886