使用retrofit處理網(wǎng)絡請求時,通常解析的結(jié)果是通過GsonConverterFactory或者是其他的Jackson之類的解析器來處理Json對象的解析。遇到需要解密的時候,先看返回的數(shù)據(jù):
{"retCode":200,"retDesc":"Success","ret":xxxxxx}
? ? ret里存放的是加密過的數(shù)據(jù)。
兩種套路:
一. 自定義Converter
.addConverterFactory(MyConverterFactory.create())
通??梢蕴幚韺⑺械恼埱蟮姆祷厝窟M行解密,如果我們要根據(jù)請求去判斷是否解密,因為在Converter里無法獲取到Reqest和Response對象,所有如何判斷這個接口請求是否需要解密結(jié)果是個問題。
二.將對象解析成json后處理加密的ret
結(jié)合RxJava使用map轉(zhuǎn)換。
使用注解
public interface GitHubService {
@GET("users/{user}/repos")
?Call> listRepos(@Path("user") String user);
?}
Retrofit構(gòu)造請求時,使用了注解@GET,再看看Converter里的代碼
發(fā)現(xiàn)參數(shù)里返回里傳了annotations數(shù)組,所以,遍歷它吧,里面包含了所有你寫請求時加的注解
@Override?
public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofitretrofit) {?
????boolean encryt = false;??
????for (int i = 0; i < annotations.length; i++) {???
????????if (annotations[i].annotationType().toString().equals(ENCRYT.class.toString())) {???????
????????????encryt = true;?????
????????}????
? ? ?}???
return new MyResponseBodyConverter<>(gson, type, encryt);
}
自定義一個注解@XXX,請求時寫上標記你的請求類型,加密。
然后你就可以在Converter里處理了。
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 個人淺見,歡迎批評!