使用retrofit處理網(wǎng)絡(luò)請(qǐng)求時(shí),通常解析的結(jié)果是通過(guò)GsonConverterFactory或者是其他的Jackson之類的解析器來(lái)處理Json對(duì)象的解析。遇到需要解密的時(shí)候,先看返回的數(shù)據(jù):
{"retCode":200,"retDesc":"Success","ret":xxxxxx}
? ? ret里存放的是加密過(guò)的數(shù)據(jù)。
兩種套路:
一. 自定義Converter
.addConverterFactory(MyConverterFactory.create())
通常可以處理將所有的請(qǐng)求的返回全部進(jìn)行解密,如果我們要根據(jù)請(qǐng)求去判斷是否解密,因?yàn)樵贑onverter里無(wú)法獲取到Reqest和Response對(duì)象,所有如何判斷這個(gè)接口請(qǐng)求是否需要解密結(jié)果是個(gè)問(wèn)題。
二.將對(duì)象解析成json后處理加密的ret
結(jié)合RxJava使用map轉(zhuǎn)換。
使用注解
public interface GitHubService {
@GET("users/{user}/repos")
?Call> listRepos(@Path("user") String user);
?}
Retrofit構(gòu)造請(qǐng)求時(shí),使用了注解@GET,再看看Converter里的代碼
發(fā)現(xiàn)參數(shù)里返回里傳了annotations數(shù)組,所以,遍歷它吧,里面包含了所有你寫(xiě)請(qǐng)求時(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);
}
自定義一個(gè)注解@XXX,請(qǐng)求時(shí)寫(xiě)上標(biāo)記你的請(qǐng)求類型,加密。
然后你就可以在Converter里處理了。
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 個(gè)人淺見(jiàn),歡迎批評(píng)!