android retrofit入门,Android开发 retrofit入门讲解
前言
retrofit基于okhttp封裝的網絡請求框架,網絡請求的工作本質上是 OkHttp 完成,而 retrofit 僅負責網絡請求接口的封裝.如果你不了解OKhttp建議你還是先了解它在來學習使用retrofit,傳送門:Android 開發(fā) 框架系列 OkHttp使用詳解
Retrofit優(yōu)勢,就是簡潔易用,解耦,擴展性強,可搭配多種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
老規(guī)矩按思維順序講解demo
1.創(chuàng)建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.創(chuàng)建數據返回后的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.創(chuàng)建一個網絡請求接口
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);
}
總結
以上是生活随笔為你收集整理的android retrofit入门,Android开发 retrofit入门讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鸿蒙系统第二款产品,鸿蒙OS第二款产品
- 下一篇: 三星t800Android 6.0,6.