之前項目的數據獲取都是通過Okhttp來獲取的,但是聽說retrofit獲取數據跟優越,就嘗試使用retrofit在同樣的數據接口上獲取數據,由於是第一次所以走了很多彎路,現在做下記錄方便自己或者大家以後直接使用,減少撞牆,節省開發時間。
使用Retrofit大概分爲以下幾個步驟:
1、首先的在build.gradle 中添加如下依賴
implementation 'com.squareup.retrofit2:retrofit:2.4.0' // 轉換器 將結果通過gson將json串轉換爲model implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
2、創建Retrofit對象
Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); HttpJson httpJson = retrofit.create(HttpJson.class);//這是get請求的接口
請求中的完整路徑是:http://login.xjymedia.com/api/Device/GetDeviceTime?device=device
HttpJson代碼如下:
@GET("GetDeviceTime") Call<ResponseBody> getHaoMa(@Query("deviceId") String deviceId);//做的是原生數據請求,之前沒有注意,只用其他方式,導致一直拿不到數據
3、發起網絡請求
Call<ResponseBody> call = httpJson.getHaoMa("00000000116");//這裏Call裏面的內容必須與HttpJson內的Call內的一致 call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(@Nullable Call<ResponseBody> call, @NonNull Response<ResponseBody> response) { try { String jsonStr = new String(response.body().bytes());//把原始數據轉爲字符串 KLog.e("retrofit獲取到的數據", jsonStr); jsonToObj(jsonStr);//這是對字符串數據解析具體數據方法 } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(@NonNull Call<ResponseBody> call, Throwable t) { KLog.e("請求失敗!", t.toString()); } }); }
這就完成了get方法的數據請求,寫得不好的地方,歡迎大家指正。其他請求數據方式,後面學習了,在寫新的博客。