依赖代码:
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使用,一般用于文件上传
@Header:添加http header
@Headers:跟@Header作用一样,只是使用方式不一样,@Header是作为请求方法的参数传入,@Headers是以固定方式直接添加到请求方法上
如果需要RxJava+Retrofit的结合使用
推荐博客专栏: http://blog.youkuaiyun.com/column/details/13297.html
附上源代码:https://github.com/wzgiceman/RxjavaRetrofitDemo-master
@源码非本人所编写,仅供参考