您的位置:首页 > 理论基础 > 计算机网络

retrofit2 的使用 ,绝对干货,希望收藏 rxjava + retrofit + okhttp

2018-01-02 17:34 447 查看

依赖代码:

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'


OkHttp配置代码:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.addNetworkInterceptor(authorizationInterceptor)
.build();


Retrofit配置:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
apiService = retrofit.create(ApiService.class);


retrofit常用注解:

@Query、@QueryMap:用于Http Get请求传递参数

@Field:用于Post方式传递参数,需要在请求接口方法上添加@FormUrlEncoded,即以表单的方式传递参数

@Body:用于Post,根据转换方式将实例对象转化为对应字符串传递参数.比如Retrofit添加GsonConverterFactory则是将body转化为gson字符串进行传递

@Path:用于URL上占位符

@Part:配合@Multipart使用,一般用于文
4000
件上传

@Header:添加http header

@Headers:跟@Header作用一样,只是使用方式不一样,@Header是作为请求方法的参数传入,@Headers是以固定方式直接添加到请求方法上

如果需要RxJava+Retrofit的结合使用

推荐博客专栏: http://blog.csdn.net/column/details/13297.html

附上源代码:https://github.com/wzgiceman/RxjavaRetrofitDemo-master

@源码非本人所编写,仅供参考
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: