Retrofit 是 square 公司出品的開源的 http 請求框架。
其面向接口和注解的編程方式,使我們的http請求變的更加簡單,我們只需要創(chuàng)建一個Api接口類,寫上服務(wù)器的接口方法即可,而無需關(guān)心其實現(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:為了避免項目中的多次創(chuàng)建Retrofit,可以配合dagger2實現(xiàn)單例注入。
其雖然提供了簡便的編程方式,但接口的標準比較固定:
baseUrl + apiUrl 的方式
而我們服務(wù)器端提供的接口可能并不一定按照這種方式定義,比如:
需求1:服務(wù)器端要配合app的需求調(diào)整其返回的數(shù)據(jù)的格式及業(yè)務(wù)邏輯,為保證兼容以前的 app 的業(yè)務(wù)需要,我們可能要告訴服務(wù)器某個接口的版本,所以我們可能需要傳入接口的版本信息。
方案1:最簡單實現(xiàn)是直接在接口上加上版本信息:
@POST("200800\login")
@FormUrlEncoded
Call<BaseResponseResult<User>> login(@Field("Phone") String phone, @Field("Password") String password);
但這樣的話,如果要更改好多接口的版本可能要改的信息比較多,也不符合設(shè)計的原則。
由于Retrofit本身的實現(xiàn)基于注解,所以我們可以擴展注解的方式實現(xiàn),也符合其設(shè)計標準。
方案2:
// kotlin 代碼
// 可以注解接口類,修改所有的接口的版本;亦可以修改接口的方法修改某個接口的版本。
@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ù)器提供的接口都使用了幾個共同的參數(shù),可能每個接口可能都需要傳接口的 SC/SV 等參數(shù)做接口驗證,或者傳入手機系統(tǒng)的信息、硬件信息、app的Flavor信息。
給每個接口注解幾個固定的參數(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);
有時我們可能希望把一個類轉(zhuǎn)換到成 FieldMap 或者 QueryMap 的鍵值對的方式提交到服務(wù)器,可以使用:
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class DynamicClassQuery(val value: Array<KClass<out IDynamicQueryClass>>)
// 比如要所有接口上都注入手機的版本,系統(tǒng)信息,由于參數(shù)太多,我就準備了一個類,實現(xiàn)自動轉(zhuǎn)換。
@DynamicClassQuery(Header.class)
public interface ApiService {
...
}
// 創(chuàng)建一個統(tǒng)一的接口
interface IDynamicQueryClass {
fun toQuery(): Map<String, String?>
}
// 實現(xiàn)類,用于存放手機的版本,系統(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)附上擴展 Retrofit 的代碼:
// Retrofit
ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);
// 加入擴展的參數(shù)
args = serviceMethod.rebuildArgs(args);
// ServiceMethod
final class ServiceMethod<R, T> {
// 擴展的注解
Map<String, String> fixedFields;
Map<String, String> fixedQueries;
...
ServiceMethod(Builder<R, T> builder) {
...
// 擴展的注解
this.fixedFields = builder.fixedFields;
this.fixedQueries = builder.fixedQueries;
}
...
// 擴展我們需要的參數(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> {
...
// 擴展的注解
Map<String, String> fixedFields;
Map<String, String> fixedQueries;
...
Builder(Retrofit retrofit, Method method) {
...
// 初始化擴展的注解
this.fixedFields = new HashMap<>();
this.fixedQueries = new HashMap<>();
}
...
// 解析接口的注解,這里包含父類的注解,使用時請注意
Annotation[] classAnnotations = method.getDeclaringClass().getAnnotations();
for (Annotation annotation : classAnnotations) {
// 這個是解析我們擴展的注解的方法
parseExtendAnnotation(annotation);
}
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
...
// 加上自定義擴展注解的數(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();
}
}
}
}
}