Retrofit是什麼
Github地址
Retrofit基於okhttp封裝的網絡請求框架, 網絡請求的工作本質上是 OkHttp 完成,而 retrofit 僅負責網絡請求接口的封裝。
Retrofit優勢,就是簡潔易用,解耦,擴展性強,可搭配多種Json解析框架(例如Gson),另外還支持RxJava.
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
gson是用來解析的Json數據使用的(個人偏愛Gson),retrofit也支持其他解析工具比如fastJson
實戰使用
創建Retrofit請求基礎配置
Retrofit.Builder()就是希望你根據不同的業務創建出不同的Retrofit來搭配接口服務使用。
注意 base的網絡地址 baseUrl不能爲空,且強制要求必需以 / 斜槓結尾
private Retrofit mRetrofit;
private void initHttpBase(){
mRetrofit = new Retrofit.Builder()
.baseUrl("http://doclever.cn:8090/mock/5c3c6da33dce46264b24452b/")//base的網絡地址 baseUrl不能爲空,且強制要求必需以 / 斜槓結尾
.addConverterFactory(GsonConverterFactory.create())//使用Gson解析
.callbackExecutor(Executors.newSingleThreadExecutor())//使用單獨的線程處理 (這很重要,一般網絡請求如果不設置可能不會報錯,但是如果是下載文件就會報錯)
.build();
}
請求網絡
使用create
函數創建的接口服務。
private void postHttp(){
HttpList httpList = mRetrofit.create(HttpList.class);
Call<LoginBean> call = httpList.login("181234123", "123456");
call.enqueue(new Callback<LoginBean>() {
@Override
public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
LoginBean bean = response.body();
Log.e(TAG, "onResponse: code="+bean.getCode());
Log.e(TAG, "onResponse: message="+bean.getMessage());
}
@Override
public void onFailure(Call<LoginBean> call, Throwable t) {
Log.e(TAG, "onFailure: 網絡請求失敗="+t.getMessage());
}
});
}