Android okHttp网络请求之Retrofit+Okhttp+RxJava组合

摘要:
改装简介:改装和okHttp都来自同一所学校,也是Square的开源库。它是一个类型安全的网络请求库。改装简化了网络请求过程,基于OkHttp对其进行封装,并更彻底地解耦。例如,您可以通过注释配置请求参数,并通过工厂生成CallAdapter和Converter。您可以使用不同的请求适配器,如RxJava、Java8和Guava。

Retrofit介绍:

  Retrofit和okHttp师出同门,也是Square的开源库,它是一个类型安全的网络请求库,Retrofit简化了网络请求流程,基于OkHtttp做了封装,解耦的更彻底:比方说通过注解来配置请求参数,通过工厂来生成CallAdapter,Converter,你可以使用不同的请求适配器(CallAdapter), 比方说RxJava,Java8, Guava。你可以使用不同的反序列化工具(Converter),比方说json, protobuff, xml, moshi等等。

  • 官网 http://square.github.io/retrofit/
  • github https://github.com/square/retrofit

Retrofit+OkHttpClient使用:

1.)在build.gradle中添加如下配置
compile 'com.squareup.retrofit2:retrofit:2.1.0'
2.)初始化Retrofit
     retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(FastJsonConverterFactory.create())
                .client(mOkHttpClient)
                .build();
3.)初始化OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize);
        builder.cache(cache);
        builder.addInterceptor(interceptor);
        mOkHttpClient = builder.build();

关于okHttp的拦截器、Cache-Control等这里就不再做解说了

4.)关于ConverterFactory

对于okHttpClient的初始化我们都已经很熟悉了,对ConverterFactory初次接触多少有点陌生,其实这个就是用来统一解析ResponseBody返回数据的。

常见的ConverterFactory

  • Gsoncom.squareup.retrofit2:converter-gson
  • Jacksoncom.squareup.retrofit2:converter-jackson
  • Moshicom.squareup.retrofit2:converter-moshi
  • Protobufcom.squareup.retrofit2:converter-protobuf
  • Wirecom.squareup.retrofit2:converter-wire
  • Simple XMLcom.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

    由于项目中使用的是FastJson,所以只能自己自定义ConverterFactory,不过国内已经有大神对此作了封装(http://www.tuicool.com/articles/j6rmyi7)。

  • FastJson compile 'org.ligboy.retrofit2:converter-fastjson-android:2.0.2'
5.)定义接口 get 请求

     1.get请求 不带任何参数

public interface IApi {

    @GET("users")//不带参数get请求
    Call<List<User>> getUsers();

}

   2.get请求 动态路径 @Path使用

public interface IApi {

   @GET("users/{groupId}")//动态路径get请求
   Call<List<User>> getUsers(@Path("userId") String userId);

}

  3.get请求 拼接参数 @Query使用

public interface IApi {

    @GET("users/{groupId}")
    Call<List<User>> getUsers(@Path("userId") String userId, @Query("age")int age);

}

  3.get请求 拼接参数 @QueryMap使用

public interface IApi {

    @GET("users/{groupId}")
    Call<List<User>> getUsers(@Path("userId") String userId, @QueryMap HashMap<String, String> paramsMap);

}
6.)定义接口 post请求

   1.post请求 @body使用

public interface IApi {

    @POST("add")//直接把对象通过ConverterFactory转化成对应的参数
    Call<List<User>> addUser(@Body User user);

}

   2.post请求 @FormUrlEncoded,@Field使用

public interface IApi {

 @POST("login")
    @FormUrlEncoded//读参数进行urlEncoded
    Call<User> login(@Field("userId") String username, @Field("password") String password);

}

  3.post请求 @FormUrlEncoded,@FieldMap使用

public interface IApi {

    @POST("login")
    @FormUrlEncoded//读参数进行urlEncoded
    Call<User> login(@FieldMap  HashMap<String, String> paramsMap);

}

  4.post请求 @Multipart,@Part使用

public interface IApi {

    @Multipart
    @POST("login")
    Call<User> login(@Part("userId") String userId, @Part("password") String password);

}
7.)Cache-Control缓存控制
public interface IApi {

    @Headers("Cache-Control: max-age=640000")
    @GET("users")//不带参数get请求
    Call<List<User>> getUsers();

}
8.)请求使用

  1.返回IApi 

    /**
     * 初始化Api
     */
    private void initIApi() {
        iApi = retrofit.create(IApi.class);
    }

    /**
     * 返回Api
     */
    public static IApi api() {

        return api.iApi;
    }

  2.发送请求

    Call<String> call = Api.api().login(userId,password);
    call.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        Log.e("", "response---->" + response.body());
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        Log.e("", "response----失败");
    }
    });

Retrofit+RxJava使用:

  上面介绍了Retrofit 与OkHttp的结合,下面介绍一下Retrofit与RxJava的结合,RxJava作为当前的开源库的网红之一,Retrofit理所当然也提供了对其的支持,RxJava的强大之处强大的异步处理能力,Retrofit与RxJava的结合势必提高开发效率以及运行性能。

1.)在原来的基础上添加以下依赖

 compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1' // Retrofit的rx解析库
 compile 'io.reactivex:rxandroid:1.2.0'
 compile 'io.reactivex:rxjava:1.1.5'

2.)创建retrofit对象实例时,通过addCallAdapterFactory来添加对RxJava的支持

  /**
     * 初始化Retrofit
     */
    private void initRetrofit() {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(mOkHttpClient)
                .build();
    }

3.)定义请求接口

public interface IApi {

    @POST("system/login")
    Observable<String> systemLogin(@Body String userId, @Body String password);
}

4.)调用发送请求

Api.api().systemLogin(userId,password)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(String result) {

        }
    });

总结:

  这里简单介绍了Retrofit与Okhttp、RxJava的结合使用。

https://www.cnblogs.com/whoislcj/p/5539239.html

免责声明:文章转载自《Android okHttp网络请求之Retrofit+Okhttp+RxJava组合》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇SpringBoot与动态多数据源切换自定义动软代码模版编写下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

使用Dapper.Contrib

public T Query(string sql, object param) { using (IDbConnection dbConnection = Connection) { if (dbConnection.State == Connect...

WPF多语言化的实现

  Metro插件系统系列就暂时停一下,这次我们讨论一下WPF的资源本地化实现,主要用到的:CultureInfo,ResourceManger,MarkupExtension,RESX文件,这些都是.NET框架提供的。 项目结构: 运行结果: 可在程序运行时,实时切换语言 CultureInfo   CultureInfo类表示有关特定区域性的信息...

FastJSON反序列化学习

反序列化漏洞例子 0x00、fastJSON练习 参考上面的链接,写一个类,并用fastJSON序列化。查阅API,fastJSON的序列化函数有: public abstract class JSON { // 将Java对象序列化为JSON字符串,支持各种各种Java基本类型和JavaBean public static String...

delphi类型转换 asci与char

ord(char) = asc chr(asc) = char inttohex(int,1) = hex (string)   使用AStr[i]取AStr:String中的第i个字符时需要注意的事项:这里i表示第i个字符,并不是通常的0表示第1个,i表示第i+1个。   二位的16进制转换为10进制: function HexToInt(hex :...

C-Sharp网络编程案例解析(Socket类的使用)

Server端: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace Server {     class Program     {         static v...

java解决大文件断点续传

第一点:Java代码实现文件上传 FormFile file = manform.getFile(); String newfileName =null; String newpathname =null; String fileAddre ="/numUp"; try { InputStream stream = file.getInputStream(...