前言
retrofit基于okhttp封装的网络请求框架,网络请求的工作本质上是 OkHttp 完成,而 retrofit 仅负责网络请求接口的封装.如果你不了解OKhttp建议你还是先了解它在来学习使用retrofit,传送门:Android 开发 框架系列 OkHttp使用详解
Retrofit优势,就是简洁易用,解耦,扩展性强,可搭配多种Json解析框架(例如Gson),另外还支持RxJava.但是,这篇博客不讲解RxJava配合使用的部分,与RxJava的配合使用将在另外一篇博客中讲解.
另外retrofit已经是封装的非常好了,已经最大程度上的匹配各种使用情况,所以不建议多此一举的再次封装retrofit(最多封装retrofit的单例). 再次封装不会看起来很帅也不会让你很牛逼. 只会让你看起来更蠢.把已经很拓展很解耦的实现全部破坏.
Github地址
依赖
如果你不需要使用RxJava模式,那么你只需要依赖下面2个:
implementation 'com.squareup.retrofit2:retrofit:2.6.2'implementation'com.squareup.retrofit2:converter-gson:2.4.0'
gson是用来解析的Json数据使用的(个人偏爱Gson),retrofit也支持其他解析工具比如fastJson
简单的Demo
老规矩按思维顺序讲解demo
1.创建Retrofit请求基础配置
Retrofit配置好后,可以全局使用这一个Retrofit用来请求网络(所以你可以实现单例以全局使用),当然下面的代码只是demo:
privateRetrofit mRetrofit;private voidinitHttpBase(){
mRetrofit= newRetrofit.Builder()
.baseUrl("http://doclever.cn:8090/mock/5c3c6da33dce46264b24452b/")//base的网络地址
.addConverterFactory(GsonConverterFactory.create())//使用Gson解析
.build();
}
2.创建数据返回后的Bean类
public classLoginBean {private intcode;privateString message;public intgetCode() {returncode;
}public void setCode(intcode) {this.code =code;
}publicString getMessage() {returnmessage;
}public voidsetMessage(String message) {this.message =message;
}
}
2.创建一个网络请求接口
public interfaceHttpList {
@FormUrlEncoded//注解表示from表单 还有@Multipart 表单可供使用 当然你也可以不添加
@POST("test/login_test") //网络请求路径
Call login(@Field("number") String number, @Field("password") String password);
}
注意,这是一个接口类. LoginBean则是数据返回后的Bean类(Retrofit会自动使用导入的Gson解析)
3.请求网络
private voidpostHttp(){
HttpList httpList= mRetrofit.create(HttpList.class);
Call call = httpList.login("181234123", "123456");
call.enqueue(new Callback() {
@Overridepublic void onResponse(Call call, Responseresponse) {
LoginBean bean=response.body();
Log.e(TAG,"onResponse: code="+bean.getCode());
Log.e(TAG,"onResponse: message="+bean.getMessage());
}
@Overridepublic void onFailure(Callcall, Throwable t) {
Log.e(TAG,"onFailure: 网络请求失败="+t.getMessage());
}
});
}
这样,我们就完成了一个网络请求.是不是特别简单
如何停止网络请求
如何添加Header头
以固定数据的形式添加头信息
public interfaceHttpList {
@Headers({"content1:one","content2:two"})
@POST("test/logout_test")
Calllogout1();
}
以非固定数据的形式添加头信息
public interfaceHttpList {
@POST("test/logout_test")
Call logout2(@Header("content") String content);
}