android retrofit入门,Android开发 retrofit入门讲解
前言
retrofit基于okhttp封裝的網(wǎng)絡(luò)請(qǐng)求框架,網(wǎng)絡(luò)請(qǐng)求的工作本質(zhì)上是 OkHttp 完成,而 retrofit 僅負(fù)責(zé)網(wǎng)絡(luò)請(qǐng)求接口的封裝.如果你不了解OKhttp建議你還是先了解它在來(lái)學(xué)習(xí)使用retrofit,傳送門:Android 開發(fā) 框架系列 OkHttp使用詳解
Retrofit優(yōu)勢(shì),就是簡(jiǎn)潔易用,解耦,擴(kuò)展性強(qiáng),可搭配多種Json解析框架(例如Gson),另外還支持RxJava.但是,這篇博客不講解RxJava配合使用的部分,與RxJava的配合使用將在另外一篇博客中講解.
另外retrofit已經(jīng)是封裝的非常好了,已經(jīng)最大程度上的匹配各種使用情況,所以不建議多此一舉的再次封裝retrofit(最多封裝retrofit的單例). 再次封裝不會(huì)看起來(lái)很帥也不會(huì)讓你很牛逼. 只會(huì)讓你看起來(lái)更蠢.把已經(jīng)很拓展很解耦的實(shí)現(xiàn)全部破壞.
Github地址
依賴
如果你不需要使用RxJava模式,那么你只需要依賴下面2個(gè):
implementation 'com.squareup.retrofit2:retrofit:2.6.2'implementation'com.squareup.retrofit2:converter-gson:2.4.0'
gson是用來(lái)解析的Json數(shù)據(jù)使用的(個(gè)人偏愛(ài)Gson),retrofit也支持其他解析工具比如fastJson
簡(jiǎn)單的Demo
老規(guī)矩按思維順序講解demo
1.創(chuàng)建Retrofit請(qǐng)求基礎(chǔ)配置
Retrofit配置好后,可以全局使用這一個(gè)Retrofit用來(lái)請(qǐng)求網(wǎng)絡(luò)(所以你可以實(shí)現(xiàn)單例以全局使用),當(dāng)然下面的代碼只是demo:
privateRetrofit mRetrofit;private voidinitHttpBase(){
mRetrofit= newRetrofit.Builder()
.baseUrl("http://doclever.cn:8090/mock/5c3c6da33dce46264b24452b/")//base的網(wǎng)絡(luò)地址
.addConverterFactory(GsonConverterFactory.create())//使用Gson解析
.build();
}
2.創(chuàng)建數(shù)據(jù)返回后的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)建一個(gè)網(wǎng)絡(luò)請(qǐng)求接口
public interfaceHttpList {
@FormUrlEncoded//注解表示from表單 還有@Multipart 表單可供使用 當(dāng)然你也可以不添加
@POST("test/login_test") //網(wǎng)絡(luò)請(qǐng)求路徑
Call login(@Field("number") String number, @Field("password") String password);
}
注意,這是一個(gè)接口類. LoginBean則是數(shù)據(jù)返回后的Bean類(Retrofit會(huì)自動(dòng)使用導(dǎo)入的Gson解析)
3.請(qǐng)求網(wǎng)絡(luò)
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: 網(wǎng)絡(luò)請(qǐng)求失敗="+t.getMessage());
}
});
}
這樣,我們就完成了一個(gè)網(wǎng)絡(luò)請(qǐng)求.是不是特別簡(jiǎn)單
如何停止網(wǎng)絡(luò)請(qǐng)求
如何添加Header頭
以固定數(shù)據(jù)的形式添加頭信息
public interfaceHttpList {
@Headers({"content1:one","content2:two"})
@POST("test/logout_test")
Calllogout1();
}
以非固定數(shù)據(jù)的形式添加頭信息
public interfaceHttpList {
@POST("test/logout_test")
Call logout2(@Header("content") String content);
}
總結(jié)
以上是生活随笔為你收集整理的android retrofit入门,Android开发 retrofit入门讲解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 鸿蒙系统第二款产品,鸿蒙OS第二款产品
- 下一篇: 三星t800Android 6.0,6.