現(xiàn)在市面上已經(jīng)有了很多關(guān)于Retrofit的使用教程的博文,本篇只是我自己學(xué)習(xí)使用Retrofit時(shí)候的一個(gè)總結(jié)。本文參考自:霍丙乾 騰訊Bugly的《深入淺出 Retrofit,這么牛逼的框架你們還不來看看?》一文。
附:Retrofit首頁及官方教程
使用首先要導(dǎo)入Retrofit的依賴:
//這兩個(gè)依賴庫的版本必須要保持一致compile 'com.squareup.retrofit2:retrofit:2.1.0'//Retrofit依賴compile 'com.squareup.retrofit2:converter-gson:2.1.0'//Retrofit數(shù)據(jù)轉(zhuǎn)換的依賴,可以直接將json轉(zhuǎn)化為實(shí)體類在新建項(xiàng)目并建立依賴之后就可以開始使用Retrofit了。
這里使用聚合數(shù)據(jù)提供的接口來獲取數(shù)據(jù):
請求地址:http://op.juhe.cn/onebox/weather/query 請求參數(shù):cityname=%E5%8C%97%E4%BA%AC&dtype=json&key=19f4708ebed559eac920bbaa51b24a12 請求方式:GET
package com.wei.retrofitdemo.Interface;import com.wei.retrofitdemo.javaBean.WeatherInform;import retrofit2.Call;import retrofit2.http.GET;import retrofit2.http.Query;/** * Created by WQC on 2016/7/15. */public interface WeatherService { //用于指定請求的方式 @GET("weather/query") //具體的請求回調(diào)的方法,可以使用@Query注解來添加url中的參數(shù) Call<WeatherInform> getWeather(@Query("cityname") String cityname, @Query("dtype") String dtype, @Query("key") String key);}這里邊用到了WeatherInform這個(gè)JavaBean,可以使用AS的GsonFormat將json數(shù)據(jù)轉(zhuǎn)換成對應(yīng)的Java類:
(因?yàn)閖son轉(zhuǎn)成的Java類太長,放在文件中供下載查看) WeatherInform.java類下載地址
Url的配置方式有多種,而且這些方式可以混合使用,但是最好只用一種,不然會頭暈的。
path 是絕對路徑的形式: path = “/path”,baseUrl = “URL:http://host:port/a/b” Url = “URL:http://host:port/path”
path 是相對路徑,baseUrl 是目錄形式: path = “path”,baseUrl = “URL:http://host:port/a/b/” Url = “URL:http://host:port/a/b/path”
path 是相對路徑,baseUrl 是文件形式: path = “path”,baseUrl = “URL:http://host:port/a/b” Url = “URL:http://host:port/a/path”
path 是完整的 Url: path = “http://host:port/aa/path“,baseUrl = “http://host:port/a/b” Url = “http://host:port/aa/path”
以本文使用的URL為例(使用的是第二種方式):
path : “weather/query” baseUrl:”http://op.juhe.cn/onebox/”
所以最終的Url就是:“http://op.juhe.cn/onebox/weather/query“
1. 異步:
mWeatherCall = mWeatherService.getWeather("北京","json","19f4708ebed559eac920bbaa51b24a12"); mWeatherCall.enqueue(new Callback<WeatherInform>() { @Override public void onResponse(Call<WeatherInform> call, Response<WeatherInform> response) { if (response != null) { WeatherInform weatherInform = response.body(); if (weatherInform != null) { Log.i(TAG, "onResponse: " + weatherInform.getReason()); } }else{ Log.i(TAG, "onResponse: response is null"); } } @Override public void onFailure(Call<WeatherInform> call, Throwable t) { Log.i(TAG, "onFailure: "); } });2. 同步
try { Response<WeatherInform> weatherInform = mWeatherCall.execute(); } catch (IOException e) { e.PRintStackTrace(); }以上就是Retrofit的簡單使用方法,他使用okhttp作為底層網(wǎng)絡(luò)請求方式,在上層進(jìn)行封裝,使用注解的方式來使用。Retrofit還可以配合RxJava,RxAndroid來使用,提供更加簡潔的網(wǎng)絡(luò)請求方式。
新聞熱點(diǎn)
疑難解答