Retrofit 2.0
生活随笔
收集整理的這篇文章主要介紹了
Retrofit 2.0
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
1.簡介
2.使用介紹
?1:添加Retrofit庫的依賴?
? ????1. 在?Gradle加入Retrofit庫的依賴
? ? ???build.gradle
dependencies {compile 'com.squareup.retrofit2:retrofit:2.0.2'// Retrofit庫compile 'com.squareup.okhttp3:okhttp:3.1.2'// Okhttp庫}? ? ? 2. 添加 網絡權限?
? ? ? AndroidManifest.xml
?2:創建 接收服務器返回數據 的類?
Reception.java
public class Response{...// 根據返回數據的格式和數據解析方式(Json、XML等)定義}?3:創建 用于描述網絡請求 的接口?
public interface GetRequest_Interface {@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")Call<Translation> ?getCall();// @GET注解的作用:采用Get方法發送網絡請求// getCall() = 接收網絡請求數據的方法// 其中返回類型為Call<*>,*是接收數據的類(即上面定義的Translation類)// 如果想直接獲得Responsebody中的內容,可以定義網絡請求返回值為Call<ResponseBody> }注解類型
?
?
?
?4:創建 Retrofit 實例?
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://fanyi.youdao.com/") // 設置網絡請求的Url地址.addConverterFactory(GsonConverterFactory.create()) // 設置數據解析器.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平臺.build();
?5:創建 網絡請求實例 并 配置網接口絡請求參數?
// 創建 網絡請求接口 的實例GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);//對 發送請求 進行封裝Call<Response> call = request.getCall();
?6:發送網絡請求(異步 / 同步)
? ? ? ? ? ?封裝了 數據轉換、線程切換的操作
/發送網絡請求(異步)call.enqueue(new Callback<Translation>() {//請求成功時回調@Overridepublic void onResponse(Call<Translation> call, Response<Translation> response) {//請求處理,輸出結果response.body().show();}//請求失敗時候的回調@Overridepublic void onFailure(Call<Translation> call, Throwable throwable) {System.out.println("連接失敗");}});// 發送網絡請求(同步) Response<Reception> response = call.execute();?7: 處理服務器返回的數據
?
?
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Retrofit 2.0的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CAD2015软件安装资料及教程
- 下一篇: RxJava2