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
Jacksonsegmentfault
Simple XML
com.squareup.retrofit2:converter-simplexml:2.0.2api
Protobuf
com.squareup.retrofit2:converter-protobuf:2.0.2服務器
Moshirestful
Wire
com.squareup.retrofit2:converter-wire:2.0.2網絡
Scalars
Retrofit支持多種網絡請求適配器方式:guava、Java8和rxjava
Android 提供默認的 CallAdapter,不須要添加網絡請求適配器的依賴,若要使用其餘網絡適配器,則須要按照需求在Gradle添加依賴
網絡請求適配器
Gradle依賴
guava
Java8
com.squareup.retrofit2:adapter-java8:2.0.2
rxjava
// 建立 網絡請求接口 的實例 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,更多幹貨等你來拿喲.
更多精彩文章請關注