先写应用,后写原理分析。
引用:
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'io.reactivex:rxjava:1.1.9'
compile 'io.reactivex:rxandroid:1.2.1'
步骤1,创建数据Model
这里根据服务器返回的result结构,定义了一个model
public class UserInfoResult implements Serializable{
public User data = null;
public class User implements Serializable {
public String uid;
public String email = null;
public String uname = null;
public String phone = null;
}
}
步骤2,创建接口
使用GET注解,描述接口的路径。接口参数使用QueryMap,即可灵活添加query参数。Observable<>中定义返回的类型。
这里Observable是Rxjava专用,不用Rxjava的话使用Call即可。
public interface IsLoginInterface {
@GET("apis/is_token_login")
Call<UserInfoResult> callIsLogin(@QueryMap Map<String, String> map);
@GET("apis/is_token_login")
Observable<UserInfoResult> callIsLogin2(@QueryMap Map<String, String> map);
}
步骤3,创建Retrofit实例
baseUrl比如http://www.baidu.com/。如果你的项目要请求多个后台,那么就需要实例化多个retrofit了。
Retrofit retrofit = Retrofit.Builder()
.baseUrl(mBaseUrl) // 设置baseUrl,一般采用服务器的域名
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(FastJsonConverterFactory.create()) //设置使用FastJson解析
.client(new HttpClientFactory.Builder().build())
.build();
CallAdapter是请求适配器,默认会使用Android,这里使用Rxjava。
Converter是数据解析器,因为比较习惯Fastjson,所以参考GsonConverter自己写了一个,很简单。
如果喜欢用gson的话,用GsonConverterFactory.create()即可。记得加依赖com.squareup.retrofit2:converter-gson:2.0.2
public class FastJsonConverterFactory extends Converter.Factory{
public static FastJsonConverterFactory create() {
return new FastJsonConverterFactory();
}
/**
* 需要重写父类中responseBodyConverter,该方法用来转换服务器返回数据
*/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new FastJsonResponseBodyConverter<>(type);
}
/**
* 需要重写父类中responseBodyConverter,该方法用来转换发送给服务器的数据
*/
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return new FastJsonRequestBodyConverter<>();
}
}
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Type type;
public FastJsonResponseBodyConverter(Type type) {
this.type = type;
}
/*
* 转换方法
*/
@Override
public T convert(ResponseBody value) throws IOException {
BufferedSource bufferedSource = Okio.buffer(value.source());
String tempStr = bufferedSource.readUtf8();
bufferedSource.close();
return JSON.parseObject(tempStr, type);
}
}
public class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
@Override
public RequestBody convert(T value) throws IOException {
return RequestBody.create(MEDIA_TYPE, JSON.toJSONBytes(value));
}
}
client这里自己写了个httpclient,加了两个过滤器用来打印日志、增加统一的header
写得有点丑,上半部分用来增加统一的header,下边用来打印日志,两个Interceptor。
public OkHttpClient build() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder = builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
String url = chain.request().url().toString();
if (isNeedAuthorization(url)) {//判断是否需要Authorization的header
Request request = chain.request()
.newBuilder()
.addHeader(AUTHORIZATION, ApiCache.getAuthorization())
.build();
return chain.proceed(request);
} else {
return chain.proceed(chain.request());
}
}
});
if (isShowLog()) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder = builder.addInterceptor(httpLoggingInterceptor);
}
return builder.build();
}
步骤4,创建步骤2中接口的实例
IsLoginInterface callInterface = retrofit.create(IsLoginInterface.class);
步骤5,请求接口
Map<String, String> params = new HashMap<>();
params.put("agenttype", "11");
params.put("device_name", "11");
params.put("token", token);
callInterface.callIsLogin2(params)//rxjava
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<UserInfoResult>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(UserInfoResult userInfoResult) {
}
});
//下边是另一种方式
Call<UserInfoResult> call = callInterface.callIsLogin(params);/call方式
call.enqueue(new Callback<UserInfoResult>() {//异步请求
@Override
public void onResponse(Call<UserInfoResult> call, Response<UserInfoResult> response) {
Log.d(TAG, response.body().toString());
}
@Override
public void onFailure(Call<UserInfoResult> call, Throwable t) {
}
});
// 同步请求
Response<UserInfoResult> response = call.execute();