Retrofit網路開源庫
阿新 • • 發佈:2018-11-05
網路開源庫有很多,不過目前最為流行或者用到最多有三個volley、okhttp、retrofit不過博主個人感覺xutil也挺好的(具體用法我會在微信中推廣)
廢話不多說先上原始碼
原始碼連結 點選開啟連結
github上的原始碼 點選開啟連結
簡單介紹
Retrofit和okhttp是由同一個人開放的已經被谷歌所認證,若專案中存有okhttp時,Retrofit會預設使用okhttp進行網路的請求。Retrofit可以進行處理
處理GET和POST常 用的請求外還可以處理PUT、DELETE等網路請求,通過註釋的方式來進行把HTTP請求轉換成java的介面。
整合到Retrofit到專案
整合Retrofit到專案中是通過在gradle指令碼中新增
<span style="font-family:Microsoft YaHei;font-size:14px;color:#333333;"> compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'</span>
匯入第二個的目的是為了將請求返回的json物件轉換成model
請求API註解成介面
既然要獲取json資料我們就按照github上的網址來進行獲取json,當然其中的fanloveoupao你可以換成自己的github賬號
<span style="font-size:18px;"> https://api.github.com/users/fanloveoupao</span>
Json資料模式
在構建對應的資料物件model時我推薦一款AndroidStudio的外掛,使用快捷方便{ "login": "fanloveoupao", "id": 15713500, "avatar_url": "https://avatars.githubusercontent.com/u/15713500?v=3", "gravatar_id": "", "url": "https://api.github.com/users/fanloveoupao", "html_url": "https://github.com/fanloveoupao", "followers_url": "https://api.github.com/users/fanloveoupao/followers", "following_url": "https://api.github.com/users/fanloveoupao/following{/other_user}", "gists_url": "https://api.github.com/users/fanloveoupao/gists{/gist_id}", "starred_url": "https://api.github.com/users/fanloveoupao/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/fanloveoupao/subscriptions", "organizations_url": "https://api.github.com/users/fanloveoupao/orgs", "repos_url": "https://api.github.com/users/fanloveoupao/repos", "events_url": "https://api.github.com/users/fanloveoupao/events{/privacy}", "received_events_url": "https://api.github.com/users/fanloveoupao/received_events", "type": "User", "site_admin": false, "name": null, "company": null, "blog": null, "location": null, "email": null, "hireable": null, "bio": null, "public_repos": 27, "public_gists": 0, "followers": 0, "following": 0, "created_at": "2015-11-08T09:43:40Z", "updated_at": "2016-03-31T05:45:12Z" }
GsonFormat
這個外掛將model的生成自動化了是不是快捷方便了好多。 言歸正傳,現在介紹將http api轉化成Java介面 首先定義介面
public interface GetRetrofit {
//https://api.github.com/users/fanloveoupao
//進行拼接型的get請求
@GET("/users/{user}")
Call<GetModel> getFreed(@Path("user") String user);
}
</pre><div>把請求體封裝成方法</div><div><pre name="code" class="java">/**
* 這裡我們使用@GET註解進行get請求,@GET("str");表示這裡的
* 請求地址是baseurl+str,{user}這裡的user將會被方法getFreed裡面的string所替代最後拼接成
* 最終的請求路徑
*/
@GET("users/{user}")
public Call<GetModel> getSingle(@Path("user") String user);
個人推薦把註解的請求體定義成方法這個,因為一個專案中的請求體不止一個,不可能一個請求定義一個接入這樣不但工作量大而且還不容易維護。
執行請求
public void getPath(View view) {
//執行請求
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create()).build();
GetRetrofit getRetrofit = retrofit.create(GetRetrofit.class);
Call<GetModel> modelCall = getRetrofit.getSingle("fanloveoupao");
// Call<GetModel> modelCall = getRetrofit.getFreed("fanloveoupao");
modelCall.enqueue(new Callback<GetModel>() {
@Override
public void onResponse(Response<GetModel> response, Retrofit retrofit) {
Log.i("TAG", "40行" + response.body().getLogin());
}
@Override
public void onFailure(Throwable t) {
}
});
這裡先構建Retrofit的物件注意別把包導錯了,因為要把返回的json資料轉換成Model物件所以加入了GsonConverterFactort進行過轉換
最後利用http中的介面生成Call物件,然後進行呼叫enqueue佇列進行執行。最後別忘記新增網路的許可權,不然執行不了。
這裡的拼接只是請求的路徑比較段的時候,如果請求的路徑比較長呢?比如下面這個
http://write.blog.csdn.net/postedit?ref=toolbar&ticket=ST-162678-dlniBZKaPKcmHbhEygKY-passport.csdn.net
這裡我們引入鍵值對,或者說另外一種註解@Query、@QueryMap
請求的引數過長時,但只有一個鍵值對時
@GET("/home")
public Call<GetModel> getLong(@Query("t") String value);
這裡拼接出的url就是https://api.github.com/users/home?t=value
很長的路徑多個鍵值對時:
//更長時可以考慮
@GET("/home")
public Call<GetModel> getMany(@QueryMap Map<String, String> optiom);
多個拼接,擁有多個鍵值對時
https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=1212120055
多個鍵值對拼接到路徑中
Map<String,String> a=new HashMap<>()
a.put("t","home/index");
a.put("lang","zh_CN");
a.put("oken","1212120055");
我們知道常用的請求除了GET更多的是用POST,GET和POST的其中一個區別就是引數的位置,GET是把引數放進路徑中而POST是放進請求體中的 按照這個不同我們來進行分析關於POST的請求
@FormUrlEncoded //post請求一定要加這個
@POST("/login")
public Call<GetModel> login(@Field("username") String user,@Field("password") String pass);
執行請求的方式和上面GET的執行是一樣的這裡不做太多解釋。
Retrofit可以將HTTP的API請求轉化成Java介面物件那麼,這裡就講解一下他的其他註解方式(出現過的)
配置body的post中
<span style="font-family:Microsoft YaHei;">@FormUrlEncoded
@POST("/index.php")
public Call<GetModel> postBody(@Body GetModel getModel);</span>
還有一點需要特別注意的是在POST請求前一定要加@FormUrlEncoded。
配置請求頭 /**
* 關於配置請求頭的
* Http請求是存在請求頭的有時我們要填寫或者配置,不過一般我們用不到
* 不過還是簡單的做下講解吧
*
* */
@GET("/user")
public Call<GetModel> getHeader(@Header("author") String autj);
關於Retrofit的網路請求我知道就大致這麼多了,對於Retrofit的理解我也是剛學到的如果有錯誤的或者不嚴密的定及時更改。
最後還是老套路,關注微信公眾號走一走,掃描頭像“激情”-“落料”!
阿里嘎多大家的支援,相信最好的自己慢慢去完善自己總有一天你會發現你的努力和積累也是可以有收穫的。 ---雞湯博主!