Retrofit
是最受開發者歡迎的一個網絡請求庫retrofit:2.5.0 - githubandroid
Retrofit
是Square公司開發的一款針對Android網絡請求的框架,遵循Restful設計風格,底層基於OkHttp.dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
api 'com.squareup.retrofit2:converter-gson:2.0.2'
}
複製代碼
<uses-permission android:name="android.permission.INTERNET"/>
複製代碼
public class ResultData{
...
// 根據返回數據的格式和數據解析方式(Json、XML等)定義
}
複製代碼
public interface GetRequestInterface {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<ResultData> getCall();
// @GET註解的做用:採用Get方法發送網絡請求
// getCall() = 接收網絡請求數據的方法
// 其中返回類型爲Call<*>,*是接收數據的類(即上面定義的Translation類)
// 若是想直接得到Responsebody中的內容,能夠定義網絡請求返回值爲Call<ResponseBody>
}
複製代碼
具體做用以及解釋請自行前往官方文檔查看,這裏就不一一解釋了git
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") // 設置網絡請求的公共Url地址
.addConverterFactory(GsonConverterFactory.create()) // 設置數據解析器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺
.build();
複製代碼
數據解析器 Gradle依賴github
Gson com.squareup.retrofit2:converter-gson:2.0.2json
Simple XML com.squareup.retrofit2:converter-simplexml:2.0.2segmentfault
Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2api
Wire com.squareup.retrofit2:converter-wire:2.0.2bash
網絡請求適配器 Gradle依賴服務器
Java8 com.squareup.retrofit2:adapter-java8:2.0.2restful
// 建立 網絡請求接口 的實例
GetRequestInterface request = retrofit.create(GetRequestInterface.class);
//對 發送請求 進行封裝
Call<ResultData> call = request.getCall();
複製代碼
/發送網絡請求(異步)
call.enqueue(new Callback<ResultData>() {
//請求成功時回調
@Override
public void onResponse(Call<ResultData> call, Response<ResultData> response) {
//處理結果
}
//請求失敗時候的回調
@Override
public void onFailure(Call<ResultData> call, Throwable throwable) {
//提示失敗
}
});
// 發送網絡請求(同步)
Response<ResultData> response = call.execute();
複製代碼
//發送網絡請求(異步)
call.enqueue(new Callback<ResultData>() {
//請求成功時回調
@Override
public void onResponse(Call<ResultData> call, Response<ResultData> response) {
// 對返回數據進行處理
response.body();//拿到ResultData對象進行數據操做
}
//請求失敗時候的回調
@Override
public void onFailure(Call<ResultData> call, Throwable throwable) {
System.out.println("鏈接失敗");
}
});
// 發送網絡請求(同步)
Response<ResultData> response = call.execute();
// 對返回數據進行處理
response.body().blabla;
複製代碼
關於Retrofit 2.5的簡單介紹到這裏就結束了,感謝閱讀.
歡迎關注做者darryrzhong,更多幹貨等你來拿喲.
更多精彩文章請關注