本文共 4267 字,大约阅读时间需要 14 分钟。
本文已授权微信公众号:鸿洋(hongyangAndroid)在微信公众号平台原创首发。
前面我们讨论了使用Retrofit时怎样去设置OKHttp,包括持久化管理Cookie、设置网络超时、设置打印拦截器、设置缓存、Header等等,详细可查看
今天我们讨论的主题是怎么封装回调才能完美的适应自己的需求。我们都知道代码风格是每个人都有自己的风格,不可能完全一样,那么我们写出来的代码怎样能够尽可能的去满足需求呢?换句话说怎样才能设计出高可用、高解耦、高可维护的代码架构呢?其实本人也是渣渣一个,看了一些别人的代码再加上自己的理解,今天把自己在用Retrofit时的一些想法分享给大家。在开始用Retrofit的时候在网上一搜,搜出来好多教程,而且口碑很好,所以我打算新的项目由原来的Xutils框架转战Retrofit。
Retrofit和Java领域的ORM概念类似, ORM把结构化数据转换为Java对象,而Retrofit 把REST API返回的数据转化为Java对象方便操作。同时还封装了网络代码的调用。
看了一些资料后大致了解到,Retrofit 2.0利用注解的形式将我们访问服务器的URL以及参数封装成了java对象,而OKHttp依旧去执行网络请求。现在网上的教程一般都告诉我们了怎样去使用Retrofit(随意找了一个教程):
1.首先定义一个接口:public interface APIService { @GET("/users/{user}/repos") ListlistRepos(@Path("user") String user);}
2.接着通过Retrofit.Builder()去创建这个url以及参数
Retrofit retrofit = new Retrofit.Builder() .baseUrl("xxx") .addConverterFactory(GsonConverterFactory.create()) .build(); APIService service = retrofit.create(APIService.class);
3.最后通过定义Call去执行网络请求
Callcall = apiService.getUser(username);call.enqueue(new Callback () { @Override public void onResponse(Response response) { int statusCode = response.code(); User user = response.body(); } @Override public void onFailure(Throwable t) { // Log error here since request failed }});
然后我们就能在网络请求成功失败的回调出去更新UI了。
很简单的实现了一个网络请求,当然我在刚开始的时候一直也都是这么使用的,因为Retrofit自己封装了JSON解析的过程,我们只需在建造Retrofit的时候加入addConverterFactory(GsonConverterFactory.create())
就可以了,但是得保证我们定义的API接口的时候Call里面的bean要和服务器返回的接口一一对应,否则这个字段就会为null,甚至网络请求失败报错json转化异常。
我们都知道服务器返回的结果一般都是下面这种格式的:
public class BaseCallModel{ public int errno; public String msg; public T data;}
定义一个BaseCallModel,利用泛型去适合服务器返回的所有的bean,而你在定义一个API接口的时候就可以这样定义:
@GET("user/login")Call> doLogin(@Query("email") String email, @Query("password") String pwd);
自定义完响应体之后,那么问题又来了,error_code会有不同的值,而不同的值需要我们所做的操作不同,举个例子,我们的需求是
import java.net.ConnectException;import java.net.SocketTimeoutException;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;/** * Created by Hankkin on 2016/6/4. */public abstract class MyCallbackimplements Callback { @Override public void onResponse(Call call, Response response) { if (response.raw().code() == 200) { //200是服务器有合理响应 if(response.body().errno == 0){ onSuc(response); } else if (response.body().errno == 1){ } else if (response.body().errno == 2){ onAutoLogin(); } else if (){ } . . . else { onFail(response.body().msg); } } else { //失败响应 onFailure(call, new RuntimeException("response error,detail = " + response.raw().toString())); } } @Override public void onFailure(Call call, Throwable t) { //网络问题会走该回调 if(t instanceof SocketTimeoutException){ // }else if(t instanceof ConnectException){ // }else if(t instanceof RuntimeException){ // } onFail(t.getMessage()); } public abstract void onSuc(Response response); public abstract void onFail(String message); public abstract void onAutoLogin();}
我自定义了一个抽象类实现了Retrofit的CallBack<>,OnResponse()方法里面去判断网络请求正常的各种情况,onFailure()方法里面则是网络有问题会走该回调。而OnResponse()回调中也有可能网络请求失败,根据response.raw().code()去判断;然后你也可以根据异常出现的状况去执行不同的UI,例如:
if(t instanceof SocketTimeoutException){ // }else if(t instanceof ConnectException){ // }else if(t instanceof RuntimeException){ // }
好了这样用起来就很爽了,如果有不合适不妥当的地方,还希望大家多多指教,共同进步。
最后分享几个不错的Retrofit博客吧: