泉州网站建设-泉州网站建设,企业营销型网站建设的可行性分析,济南网页制作设计营销,网站要挂工商标识怎么做Retrofit介绍#xff1a;Retrofit和okHttp师出同门#xff0c;也是Square的开源库#xff0c;它是一个类型安全的网络请求库#xff0c;Retrofit简化了网络请求流程#xff0c;基于OkHtttp做了封装#xff0c;解耦的更彻底:比方说通过注解来配置请求参数#xff0c;通过…Retrofit介绍Retrofit和okHttp师出同门也是Square的开源库它是一个类型安全的网络请求库Retrofit简化了网络请求流程基于OkHtttp做了封装解耦的更彻底:比方说通过注解来配置请求参数通过工厂来生成CallAdapterConverter你可以使用不同的请求适配器(CallAdapter), 比方说RxJavaJava8, Guava。你可以使用不同的反序列化工具(Converter)比方说json, protobuff, xml, moshi等等。官网 http://square.github.io/retrofit/github https://github.com/square/retrofitRetrofitOkHttpClient使用1.)在build.gradle中添加如下配置compile com.squareup.retrofit2:retrofit:2.1.02.)初始化Retrofitretrofit new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(FastJsonConverterFactory.create()).client(mOkHttpClient).build();3.)初始化OkHttpClientOkHttpClient.Builder builder new OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS)//设置超时时间.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间.writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间int cacheSize 10 * 1024 * 1024; // 10 MiBCache cache new Cache(App.getContext().getCacheDir(), cacheSize);builder.cache(cache);builder.addInterceptor(interceptor);mOkHttpClient builder.build();关于okHttp的拦截器、Cache-Control等这里就不再做解说了4.)关于ConverterFactory对于okHttpClient的初始化我们都已经很熟悉了对ConverterFactory初次接触多少有点陌生其实这个就是用来统一解析ResponseBody返回数据的。常见的ConverterFactoryGson: com.squareup.retrofit2:converter-gsonJackson: com.squareup.retrofit2:converter-jacksonMoshi: com.squareup.retrofit2:converter-moshiProtobuf: com.squareup.retrofit2:converter-protobufWire: com.squareup.retrofit2:converter-wireSimple XML: com.squareup.retrofit2:converter-simplexmlScalars (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.25.)定义接口 get 请求1.get请求 不带任何参数public interface IApi {GET(users)//不带参数get请求Call getUsers();}2.get请求 动态路径 Path使用public interface IApi {GET(users/{groupId})//动态路径get请求Call getUsers(Path(userId) String userId);}3.get请求 拼接参数 Query使用public interface IApi {GET(users/{groupId})Call getUsers(Path(userId) String userId, Query(age)int age);}3.get请求 拼接参数 QueryMap使用public interface IApi {GET(users/{groupId})Call getUsers(Path(userId) String userId, QueryMap HashMap paramsMap);}6.)定义接口 post请求1.post请求 body使用public interface IApi {POST(add)//直接把对象通过ConverterFactory转化成对应的参数Call addUser(Body User user);}2.post请求 FormUrlEncoded,Field使用public interface IApi {POST(login)FormUrlEncoded//读参数进行urlEncodedCall login(Field(userId) String username, Field(password) String password);}3.post请求 FormUrlEncoded,FieldMap使用public interface IApi {POST(login)FormUrlEncoded//读参数进行urlEncodedCall login(FieldMap HashMap paramsMap);}4.post请求 Multipart,Part使用public interface IApi {MultipartPOST(login)Call login(Part(userId) String userId, Part(password) String password);}7.)Cache-Control缓存控制public interface IApi {Headers(Cache-Control: max-age640000)GET(users)//不带参数get请求Call getUsers();}8.)请求使用1.返回IApi/*** 初始化Api*/private void initIApi() {iApi retrofit.create(IApi.class);}/*** 返回Api*/public static IApi api() {return api.iApi;}2.发送请求Call call Api.api().login(userId,password);call.enqueue(new Callback() {Overridepublic void onResponse(Call call, Response response) {Log.e(, response---- response.body());}Overridepublic void onFailure(Call call, Throwable t) {Log.e(, response----失败);}});RetrofitRxJava使用上面介绍了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.0compile io.reactivex:rxjava:1.1.52.)创建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 systemLogin(Body String userId, Body String password);}4.)调用发送请求Api.api().systemLogin(userId,password).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber() {Overridepublic void onCompleted() {}Overridepublic void onError(Throwable e) {}Overridepublic void onNext(String result) {}});总结这里简单介绍了Retrofit与Okhttp、RxJava的结合使用。https://www.cnblogs.com/whoislcj/p/5539239.html