Rxjava+RxAndroid+Retrofit组合时,会出现一个问题,先看log:

Unable to create call adapter for rx.Observable<com.baidu.retrofit.bean.IpInfo>

在build.gradle中中增加一个依赖项即可解决问题:

compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'

Retrofit使用时增加addCallAdapterFactory

this.retrofit = new Retrofit.Builder()
.baseUrl(GankApi.BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(this.gson))
.client(okHttpClient)
.build();

build.gradle中retorfit的版本一定要一致,否则就会出各种问题。

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'

延伸: Retrofit2.0 中使用问题

从2015 年开始,Retrofit 2.0 虽说一直是 Beta 版本迭代,相对于1.9来说,改动还是相当的大的。

特别提示:

由于2.0的版本中, retrofit:2.0.0-beta2 和 beta3 以后的版本改变较大。包括包名和引用方式,如果要升级的同学请慎重。

改变之处:

  1. OKHttpClient和OKHttpClient3的不同
  2. com.squareup.retrofit和com.squareup.retrofit2的不同
  3. 拦截器添加方法的不同
  4. 内部结构和使用方式的不同等

添加Gradle依赖

retrofit:2.0.0-beta2

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' // retrofit
compile 'com.google.code.gson:gson:2.5' // gson
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' // gson convertor with retrofit
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2' // rxjava extension with retrofit
compile 'com.squareup.okhttp:logging-interceptor:2.7.0'

retrofit:2.0.0-beta4

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' // retrofit
compile 'com.google.code.gson:gson:2.5' // gson
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
compile 'com.squareup.okhttp3:okhttp:3.1.2'

创建 Retrofit 常规实例

public static Retrofit initRetrofit(){
OkHttpClient httpClient = new OkHttpClient();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
}
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();//使用 gson coverter,统一日期请求格式
return new Retrofit.Builder()
.baseUrl(BaseUtil.getGlivecApiUrl())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.build();
}

/**
* 创建 RetrofitManage 服务
*
* @return
public static ApiService createApiService() {
return

拦截器:

拦截器是应用在不同场合下需要的,比如打印日志,请求添加头文件。

//注意此处和 beta3 之前的版本写法不同:
OkHttpClient client =new OkHttpClient.Builder().addInterceptor.(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Customize the request header
Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "auth-token")
.method(original.method(), original.body())
.build();

Response response = chain.proceed(request);

// Customize or return the response
return response;
}
});

转换器

目前 beta-4 开始支持以下几种 converter:

Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

同步和异步请求

和1.9不同在2.0 版本中,请求只需要一种写法

import retrofit.Call
/*Retrofit 2.0*/

public interfase ApiService{
@POST("/list")
Call<Repo> loadRepo();

//支持动态url
@POST
Call<Repo> loadRepo(@Url

异步调用

Call<Repo> call = service.loadRepo();
call.enqueue(new Callback<Repo>(){
@Override
public void onResponse(Response<Repo> response){
//从response.body()中获取结果
}
@Override
public void onFailure(Throwable t){

}
});

同步调用

Call<Repo> call
Repo repo = call.excute();

在Android中不能在主线程中调用,否则会抛出NetworkOnMainThreadException

取消请求

服务模式变成Call的原因是正在进行中的请求事务可以被取消,只用简单的使用call.cancel()就可以了。

call.cancel();

特殊需求:

如果在使用的过程中,不需要Gson以及其他转换器,只是单纯的返回 JSONObject,那这样怎么处理呢?

通过阅读源码发现,可以通过自定义转换器的方式操作:

import retrofit.Call
/*Retrofit 2.0*/

public interfase ApiService{
@POST("/list")
Call<JSONObject> loadRepo();
}

同步操作:

Call<JSONObject> call = service.loadRepo();
Repo repo = call.excute()

异步操作:

Call<JSONObject> call = service.loadRepo();
call.enqueue(new Callback<JSONObject>(){
@Override
public void onResponse(Response<JSONObject> response){
//从response.body()中获取结果
}
@Override
public void onFailure(Throwable t){

}
});

这样就完了么?不。

  1. 添加自定义Converter
    地址:​​https://github.com/brokge/Retrofit2.0-JSONCoverter​
    选择相应版本添加到项目中。(Retrofit 2.0 -beta2和Retrofit 2.0-beta4 处理方式不同)
  2. GsonConverterFactory.create(gson)换成 JsonConverterFactory.create()

代码如下:

private static Retrofit initRetrofit() {
OkHttpClient httpClient = new OkHttpClient();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
}
return new Retrofit.Builder()
.baseUrl(BaseUtil.getApiUrl())
.addConverterFactory(JsonConverterFactory.create())
.client(httpClient)
.build();

在最新版本中,retroit默认的网络请求就是用的OkHttpClient,因此,初始化Retrofit下面代码就可以了:

mRetrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();

最后再抛出完整代码:

package com.baidu.retrofit;

import android.content.Context;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitWrapper
private static RetrofitWrapper instance;
private Context mContext;
private Retrofit mRetrofit;

public RetrofitWrapper(String url) {
mRetrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}

public static RetrofitWrapper getInstance(String url){

if(null == instance){
synchronized (RetrofitWrapper.class){
instance = new RetrofitWrapper(url);
}
}
return instance;
}

public <T> T create(final Class<T> service) {
return

完整demo地址:​​https://github.com/jdsjlzx/RetrofitDemo​