我这里借鉴了许多博客。
在这里谢谢各位博主,但是我真的是不好找你们的链接。如果下次遇上了,在添加进来。希望你们不要见怪。
0.怎么封装比较好
0.1 怎么封装Heads Token,自定义参数。
0.2 怎么集中处理错误提示,以及网络Dialog,
0.3 怎么对返回Json 自动转换Bean。(感觉这个东西的做法,万变都一样。)
0.4 怎么集中输出后台的Json数据。
0 怎么封装比较好
说一说我为什么会这样,主要是想封装之后可以少些很多代码。(捂脸–主要是懒)
借鉴了网络上许多很好的封装代码(谢谢你们的分享)。
一般的写法:
先写调用Url 的接口。
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
在写怎么调用
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
想想我们我们在写一个接口,调用方法是不是有需要重新写一遍啦?
这个时候就需要懒一下咯!!!
public static <S> S provideClientApi(Class<S> serviceClass, Context mcontext) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
//.client(genericClient(mcontext))
//addCallAdapterFactory(RxJavaCallAdapterFactory.create()) Rxjava
.addConverterFactory(FastJsonConverterFactory.create())
.build();
return retrofit.create(serviceClass);
}
使用方法:
provideClientApi(GitHubService.class,ContextmContext).listRepos("tlp").enqueue(new CallBack)
这样就简化了 每次需要重新写调用方法了。
0 .1 怎么封装Heads Token,自定义参数。
参考:
http://mrljdx.com/2016/01/07/Retrofit2-0-%E6%96%B0%E7%89%B9%E6%80%A7%E7%AE%80%E4%BB%8B/
这个时候就需要提起来 OKhttp Interceptor
这个主要作用是:通过自定义拦截器,可以用于处理在发送请求或接受回复时对数据进行处理和判断。
解决问题:
1.集中处理 heads。
2.集中查看请求URL
3.集中查看请求body。
public static OkHttpClient genericClient(final Context mcontext) {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
String myTimeStamp = getMyTimeStamp();
String token = SharedConfiger.getString(mcontext, "token");
Request original = chain.request();
Request.Builder request = original
.newBuilder();
// 集中处理 heads
request
.header("参数1", "value1")
.header("参数2", value2)
.header("参数3",value3)
.method(original.method(), original.body());
// 登录之前没有Authorization
if (token != null && !token.equals("")) {
request.header("token", token);
}
return chain.proceed(request.build());
}
})
.build();
return httpClient;
}
使用方法:
public static <S> S provideClientApi(Class<S> serviceClass, Context mcontext) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.client(genericClient(mcontext))
//addCallAdapterFactory(RxJavaCallAdapterFactory.create()) Rxjava
.addConverterFactory(FastJsonConverterFactory.create())
.build();
return retrofit.create(serviceClass);
}
0.2 怎么集中处理错误提示,以及网络Dialog,
0.2.1 集中处理需要两部分才可以。
条件一: 通用的 RetrofitBaseCall // Json 对象
如:
{
Code:"200"
Msg :"成功"
Data:{
}
}
我们对应的 对象是:
public class RetrofitBaseCall<T> {
private int code;
private String message;
private T data;
}
条件二:
自定义的CallBack。
public abstract class MyCallback<T extends RetrofitBaseCall> implements Callback<T> {
private Context mcontext;
// 这里面可以写入 网络请求loading
// 取消 展示。
// 以及Toast ----交给你们思考了。
@Override
public void onResponse(Call<T> call, Response<T> response) {
//响应成功
if (response.isSuccessful()) {
if (response.body().getCode() == 999401) {
resetLogin();
return;
}
//服务器响应成功
if (response.body().getCode() == 8000) {
KLog.json("HttpLog", response.body().getData().toString());
onSuccess(response);
return;
}
if (response.body().getCode() != 8000) {
KLog.json("HttpLog", "code=" + response.body().getCode());
onFail(response.body().getMsg());
}
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
if (t instanceof SocketTimeoutException) {
onFail("网络超时");
} else if (t instanceof ConnectException) {
onFail("网络连接失败,请检查网络。");
} else if (t instanceof RuntimeException) {
onFail("网络连接失败,请检查网络。");
}
onFail(t.getMessage());
}
public abstract void onSuccess(Response<T> response);
public abstract void onFail(String message);
// token失效,重新登录。
private void resetLogin() {
GlobalApplication.getInstance().exit();
Intent intent = new Intent(mcontext, LoginActivity.class);
mcontext.startActivity(intent);
}
// public abstract void onAutoLogin();
}
怎么使用的方法?
如果返回数据是这样的
{
Code :200
meg: 成功
Data:{
name:xxxx
age: xxxx
Sex: xxxxx
}
}
Url 接口:
public interface GitHubService {
@GET("getPerson")
Call<RetrofitBaseCall<Person>>getPersonDetalis();
}
Retrofit 调用:
ServiceGenerator.provideClientApi(GitHubService.class,context).getPersonDetalis().enqueue(new MyCallback<RetrofitBaseCall<Person>>(context)){
@Override
public void onSuccess(Response<RetrofitBaseCall<Person>> response) {
//成功
}
@Override
public void onFail(String message) {
// 失败
}
});
}
0.4 怎么集中输出后台的Json数据。
答: 拦截器.
有没有感觉这个Retrofit 和 okhttp 搭配确实很厉害。类似于Spring 的环绕接收。
相同点:
1.网络请求 请求前可以拦截,(可以集中添加Heads,打印请求数据)
2.响应后 也可以拦截。(集中打印Json日志,响应时间)
做法:
// 拦截器
compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'
interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.json(message); // 自定义显示。
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
效果图: