配置Gradle
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
這里我們需要將請(qǐng)求回來(lái)的數(shù)據(jù)直接轉(zhuǎn)化為實(shí)體,恰巧官方提供了gson的轉(zhuǎn)換庫(kù),因此我們?cè)谝蕾噐etrofit的同時(shí),也要依賴converter-gson。在以后的文章里我會(huì)著重說(shuō)一下這個(gè)converterFactory,它其實(shí)類似于一個(gè)插件集成器,通過(guò)它,我們可以集成各種工具來(lái)解決我們開(kāi)發(fā)過(guò)程中的問(wèn)題以及實(shí)現(xiàn)需求。
<br />
廢話不多說(shuō),讓我們快速實(shí)現(xiàn)一個(gè)普通的get請(qǐng)求。
開(kāi)始一個(gè)簡(jiǎn)單請(qǐng)求
創(chuàng)建一個(gè)簡(jiǎn)單的bean
這里假設(shè)我們要請(qǐng)求apistore上的名人名言接口,因此我們創(chuàng)建了一個(gè)FamousInfo的bean
初始化Retrofit
<pre>
.baseUrl("http://apis.baidu.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();```</pre>
#### 創(chuàng)建一個(gè)接口
<pre>
```public interface FamousService {
@GET("/avatardata/mingrenmingyan/{path}")
Call<FamousInfo> getFamousResult(@Path("path") String path,
@Header("apiKey") String apiKey,
@Query("keyword") String keyword,
@Query("page") int page,
@Query("rows") int rows);
}```</pre>
####初始化這個(gè)接口的對(duì)象
<pre>
Call<FamousInfo> callback =retrofit.create(FamousService.class)
.getFamousResult(path,apiKey,page,rows)}
####使用這個(gè)對(duì)象獲取請(qǐng)求結(jié)果
<pre>
callback.enqueue(new Callback<FamousInfo>{
@Override
public void onResponse(Call<FamousInfo> call, Response<FamousInfo> response) {
FamousInfo bean = response.body();
}
@Override
public void onFailure(Call<FamousInfo> call, Throwable t) {
Toast.makeText(context,t.toString,Toast.LENGTH_SHORT).show();
}
});```
</pre>
這樣一個(gè)簡(jiǎn)單的get請(qǐng)求就完成了。