Retrofit 是 square 公司出品的開源的 http 請(qǐng)求框架殴瘦。
其面向接口和注解的編程方式一喘,使我們的http請(qǐng)求變的更加簡(jiǎn)單沾谜,我們只需要?jiǎng)?chuàng)建一個(gè)Api接口類敛惊,寫上服務(wù)器的接口方法即可渊鞋,而無需關(guān)心其實(shí)現(xiàn)方式,例如:
public interface ApiService {
@POST("login")
@FormUrlEncoded
Call<BaseResponseResult<User>> login(@Field("Phone") String phone, @Field("Password") String password);
}
然后直接在業(yè)務(wù)類中調(diào)用:
@Test
public void testRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://api.xxx.com/api/") // api 的域名前綴
.build();
ApiService apiService = retrofit.create(ApiService.class);
try {
String result = apiService.login("13000000000", "123456").execute().body().toString();
System.out.println(result);
} catch (IOException pE) {
pE.printStackTrace();
}
}
Note:為了避免項(xiàng)目中的多次創(chuàng)建Retrofit瞧挤,可以配合dagger2實(shí)現(xiàn)單例注入锡宋。
其雖然提供了簡(jiǎn)便的編程方式,但接口的標(biāo)準(zhǔn)比較固定:
baseUrl + apiUrl 的方式
而我們服務(wù)器端提供的接口可能并不一定按照這種方式定義特恬,比如:
需求1:服務(wù)器端要配合app的需求調(diào)整其返回的數(shù)據(jù)的格式及業(yè)務(wù)邏輯执俩,為保證兼容以前的 app 的業(yè)務(wù)需要,我們可能要告訴服務(wù)器某個(gè)接口的版本癌刽,所以我們可能需要傳入接口的版本信息役首。
方案1:最簡(jiǎn)單實(shí)現(xiàn)是直接在接口上加上版本信息:
@POST("200800\login")
@FormUrlEncoded
Call<BaseResponseResult<User>> login(@Field("Phone") String phone, @Field("Password") String password);
但這樣的話,如果要更改好多接口的版本可能要改的信息比較多显拜,也不符合設(shè)計(jì)的原則衡奥。
由于Retrofit本身的實(shí)現(xiàn)基于注解,所以我們可以擴(kuò)展注解的方式實(shí)現(xiàn)远荠,也符合其設(shè)計(jì)標(biāo)準(zhǔn)矮固。
方案2:
// kotlin 代碼
// 可以注解接口類,修改所有的接口的版本矮台;亦可以修改接口的方法修改某個(gè)接口的版本乏屯。
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class ApiVersion(val value: Int = 0 /* 0-Ignore */)
// 注解到接口方法
@ApiVersion(2008000)
@POST("login")
@FormUrlEncoded
Call<BaseResponseResult<User>> login(@Field("Phone") String phone, @Field("Password") String password);
需求2:
服務(wù)器提供的接口都使用了幾個(gè)共同的參數(shù)根时,可能每個(gè)接口可能都需要傳接口的 SC/SV 等參數(shù)做接口驗(yàn)證,或者傳入手機(jī)系統(tǒng)的信息辰晕、硬件信息蛤迎、app的Flavor信息。
給每個(gè)接口注解幾個(gè)固定的參數(shù)含友,基于注解的實(shí)現(xiàn):
// form 表單的 POST 方式
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class FixedField(val keys: Array<String>, val values: Array<String>)
// get 方式
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class FixedQuery(val keys: Array<String>, val values: Array<String>)
// 注解到接口方法
@POST("phone_login")
@FixedField(keys = {"SC", "SV"}, values = {"xxx", "yyy"})
@FormUrlEncoded
Call<BaseResponseResult<User>> login(@Field("Phone") String phone, @Field("Password") String password);
有時(shí)我們可能希望把一個(gè)類轉(zhuǎn)換到成 FieldMap 或者 QueryMap 的鍵值對(duì)的方式提交到服務(wù)器替裆,可以使用:
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class DynamicClassQuery(val value: Array<KClass<out IDynamicQueryClass>>)
// 比如要所有接口上都注入手機(jī)的版本,系統(tǒng)信息窘问,由于參數(shù)太多辆童,我就準(zhǔn)備了一個(gè)類,實(shí)現(xiàn)自動(dòng)轉(zhuǎn)換惠赫。
@DynamicClassQuery(Header.class)
public interface ApiService {
...
}
// 創(chuàng)建一個(gè)統(tǒng)一的接口
interface IDynamicQueryClass {
fun toQuery(): Map<String, String?>
}
// 實(shí)現(xiàn)類把鉴,用于存放手機(jī)的版本,系統(tǒng)信息
class Header : IDynamicQueryClass {
...
override fun toQuery(): Map<String, String?> {
val map: HashMap<String, String?> = HashMap()
val fields = Header::class.java.declaredFields;
fields.map {
map.put(it.name, it.get(this)?.toString());
}
return map;
}
}
加了這么多自定義注解儿咱,需要修改 Retrofit 的注解處理代碼庭砍,已處理我們的自定義注解。 現(xiàn)附上擴(kuò)展 Retrofit 的代碼:
// Retrofit
ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);
// 加入擴(kuò)展的參數(shù)
args = serviceMethod.rebuildArgs(args);
// ServiceMethod
final class ServiceMethod<R, T> {
// 擴(kuò)展的注解
Map<String, String> fixedFields;
Map<String, String> fixedQueries;
...
ServiceMethod(Builder<R, T> builder) {
...
// 擴(kuò)展的注解
this.fixedFields = builder.fixedFields;
this.fixedQueries = builder.fixedQueries;
}
...
// 擴(kuò)展我們需要的參數(shù)
public Object[] rebuildArgs(Object[] args) {
List<Object> argList = new ArrayList<>(Arrays.asList(args));
if (!this.fixedFields.isEmpty()) {
for (Map.Entry<String, String> entry : fixedFields.entrySet()) {
argList.add(entry.getValue());
}
}
if (!this.fixedQueries.isEmpty()) {
for (Map.Entry<String, String> entry : fixedQueries.entrySet()) {
argList.add(entry.getValue());
}
}
return argList.toArray();
}
...
static final class Builder<T, R> {
...
// 擴(kuò)展的注解
Map<String, String> fixedFields;
Map<String, String> fixedQueries;
...
Builder(Retrofit retrofit, Method method) {
...
// 初始化擴(kuò)展的注解
this.fixedFields = new HashMap<>();
this.fixedQueries = new HashMap<>();
}
...
// 解析接口的注解混埠,這里包含父類的注解怠缸,使用時(shí)請(qǐng)注意
Annotation[] classAnnotations = method.getDeclaringClass().getAnnotations();
for (Annotation annotation : classAnnotations) {
// 這個(gè)是解析我們擴(kuò)展的注解的方法
parseExtendAnnotation(annotation);
}
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
...
// 加上自定義擴(kuò)展注解的數(shù)量
parameterHandlers = new ParameterHandler<?>[parameterCount + fixedFields.size() + fixedQueries.size()];
...
// 處理自定義注解參數(shù)
int p = parameterCount;
Converter<?, String> converter = BuiltInConverters.ToStringConverter.INSTANCE;
for (Map.Entry<String, String> entry : fixedFields.entrySet()) {
parameterHandlers[p++] = new ParameterHandler.Field(entry.getKey(), converter, false);
}
for (Map.Entry<String, String> entry : fixedQueries.entrySet()) {
parameterHandlers[p++] = new ParameterHandler.Query<>(entry.getKey(), converter, false);
}
}
// 轉(zhuǎn)換自定義的注解
private void parseExtendAnnotation(Annotation annotation) {
if (annotation instanceof FixedField) {
FixedField fixedField = (FixedField) annotation;
String[] keys = fixedField.keys();
String[] values = fixedField.values();
if (keys.length != values.length) {
throw methodError("FixedField keys count (" + keys.length + ") doesn't match values count (" + values.length + ")");
}
for (int i = 0; i < keys.length; i++) {
if (keys[i] == null || keys[i].length() == 0) continue;
fixedFields.put(keys[i], values[i]);
}
isFormEncoded = true;
} else if (annotation instanceof FixedQuery) {
FixedQuery fixedQuery = (FixedQuery) annotation;
String[] keys = fixedQuery.keys();
String[] values = fixedQuery.values();
if (keys.length != values.length) {
throw methodError("FixedQuery keys count (" + keys.length + ") doesn't match values count (" + values.length + ")");
}
for (int i = 0; i < keys.length; i++) {
if (keys[i] == null || keys[i].length() == 0) continue;
fixedQueries.put(keys[i], values[i]);
}
gotQuery = true;
} else if (annotation instanceof ApiVersion) {
ApiVersion version = (ApiVersion) annotation;
this.apiVersion = version.value();
if (relativeUrl != null) {
relativeUrl = apiVersion + "/" + relativeUrl;
}
} else if (annotation instanceof SC) {
fixedFields.put("SC", ((SC) annotation).value());
} else if (annotation instanceof SV) {
fixedFields.put("SV", ((SV) annotation).value());
} else if (annotation instanceof DynamicClassQuery) {
Class<? extends IDynamicQueryClass>[] clsArray = ((DynamicClassQuery) annotation).value();
for (Class<? extends IDynamicQueryClass> cls : clsArray) {
try {
fixedQueries.putAll(cls.newInstance().toQuery());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}