感覺好久沒有寫Android的文章了衩匣,囧囧囧未檩!因為Retrofit實在是太火了戴尸, 火得我一直躍躍欲試,但是由于種種原因吧冤狡,一直都沒有用過孙蒙。周末閑來無事,利用一個以前開發(fā)中用過的服務(wù)器API來小試牛刀一下悲雳,非常簡單挎峦,記錄自己的第一次Retrofit之旅。
重要說明:由于涉及到商業(yè)機(jī)密合瓢,所以對請求的數(shù)據(jù)和服務(wù)器地址進(jìn)行了處理坦胶。自己實驗時,請換成自己的服務(wù)器晴楔。
一顿苇、添加依賴、配置項目
這一步就不詳細(xì)說了税弃,會的都會纪岁,基本就是添加兩個依賴和網(wǎng)絡(luò)訪問權(quán)限。
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
<uses-permission android:name="android.permission.INTERNET" />
二钙皮、根據(jù)服務(wù)器端返回的JSON數(shù)據(jù)配置自己的JavaBean
在項目中用Retrofit的時候蜂科,肯定和服務(wù)器端的哥們商量好了如何交互顽决,也就是說已經(jīng)知曉了服務(wù)器端會返回什么樣的數(shù)據(jù)(基本都是JSON短条,只是內(nèi)容不一樣而已)导匣,這些數(shù)據(jù)你可以直接用字符串接收,然后自己處理茸时,但是這么low的事情贡定,Retrofit肯定可以幫我處理了,用上面的converter-gson就可以自動將JSON轉(zhuǎn)成我們的對象可都,前提是需要與返回的JSON字段進(jìn)行映射缓待,默認(rèn)情況下字段名一樣就不會出什么問題,但是我卻踩了一個坑渠牲,下文會介紹旋炒。
- 服務(wù)器端返回的JSON數(shù)據(jù)如下:
{"message":"ok","list":["id":"","abstract":"","title":"","url":""},...]
- 根據(jù)上面的JSON數(shù)據(jù)創(chuàng)建JavaBean
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by yangfan on 2017/1/7.
*/
//與服務(wù)器端數(shù)據(jù)進(jìn)行字段映射
public class NewsInfo {
private String message;
private List<News> list;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<News> getList() {
return list;
}
public void setList(List<News> list) {
this.list = list;
}
public static class News {
private String id;
//@SerializedName:后面是服務(wù)器端返回的數(shù)據(jù)字段名 可以與本地不一樣 該關(guān)鍵字就是用來映射的
@SerializedName("abstract")
private String _abstract;
private String title;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String get_abstract() {
return _abstract;
}
public void set_abstract(String _abstract) {
this._abstract = _abstract;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
踩坑記錄:服務(wù)器端居然有一個abstract字段,但是這個是Java關(guān)鍵字啊签杈,怎么辦瘫镇?用@SerializedName告訴Retrofit,我想你把該字段映射成我自定義的名字答姥。
配置訪問服務(wù)器API的接口
這個就是真正的訪問服務(wù)器的本地API了铣除,我這里只用了GET,其實遠(yuǎn)不止這個功能鹦付,可以參考官方文檔尚粘。
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by yangfan on 2017/1/7.
*/
public interface NewsInterface {
//獲取服務(wù)器的新聞列表,由于新聞類型和分頁顯示的需要敲长,需要傳遞三個參數(shù)
@GET("news/list")
Call<NewsInfo> newsList(@Query("type") String type, @Query("pn") String pn, @Query("ps") String ps);
}
Activity
配置好以上信息以后郎嫁,就可以開始寫Android的程序了。因為我的程序比較簡單祈噪,所以我很快就成功獲取數(shù)據(jù)了行剂,這一塊沒怎么踩坑。
public class MainActivity extends AppCompatActivity {
private TextView tvResult;
//服務(wù)器的基地址 與 @GET("news/list")拼接
private static final String baseUrl = "http://服務(wù)器地址/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = (TextView) findViewById(R.id.tvResult);
initRetrofit();
}
private void initRetrofit() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create())
.build();
NewsInterface newsInterface = retrofit.create(NewsInterface.class);
Call<NewsInfo> callNewsInfo = newsInterface.newsList("1", "1", "10");
callNewsInfo.enqueue(new Callback<NewsInfo>() {
@Override
public void onResponse(Call<NewsInfo> call, Response<NewsInfo> response) {
//成功
if (response.code() == 200) {
//將返回的數(shù)據(jù)轉(zhuǎn)換成自定義的對象
NewsInfo newsInfo = response.body();
if(newsInfo.getMessage().equals("ok")){
//最爽的地方---直接可以進(jìn)行UI操作
tvResult.setText(newsInfo.getList().get(0).get_abstract());
}
} else {
//請求失敗
tvResult.setText("查詢失斍怠厚宰!響應(yīng)碼為:" + response.code());
}
}
@Override
public void onFailure(Call<NewsInfo> call, Throwable t) {
//請求失敗
t.printStackTrace();
tvResult.setText("查詢失敗遂填!錯誤原因:" + t.getCause());
}
});
}
}
運(yùn)行結(jié)果
Retrofit功能非常強(qiáng)大铲觉,我也看了很多文檔,上面用的只是冰山一角吓坚。目前感覺最大的好處就是可以直接在回調(diào)中操作主線程的UI撵幽,再也不需要用Handler了,其他牛逼的功能和好處待學(xué)習(xí)礁击、待發(fā)掘盐杂。