Retrofit是square出品的一個比較有名的開源網絡請求庫。
現在最新的版本是2.0
下面就說說其使用方法。
1. 首先定義一個承載接收數據的接口。如下
其中@GET後面是請求數據的子URL,可以是組合的URL,如下demo即是組合URL,owner和repo是不固定的。Contributor是服務器和終端之間的通信的數據結構
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
public static class Contributor {
public final String login;
public final intcontributions;
public Contributor(Stringlogin, int contributions) {
this.login = login;
this.contributions =contributions;
}
}
2. New一個client,由於demo返回的是json數據,所以我們可以用Gson去解析,retrofit本身是沒有轉換器的,但是square提供了一些常用數據的jar包
· Gson: com.squareup.retrofit2:converter-gson
· Jackson: com.squareup.retrofit2:converter-jackson
· Moshi: com.squareup.retrofit2:converter-moshi
· Protobuf: com.squareup.retrofit2:converter-protobuf
· Wire: com.squareup.retrofit2:converter-wire
· SimpleXML: com.squareup.retrofit2:converter-simplexml
· Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
我們可以採用addConverterFactory把轉換器加進去,如果數據格式並不在上面的常用數據格式裏面,我們也可以通過實現Converter.Factory接口來創建一個自定義的converter。
// Create a very simple REST adapter which points the GitHub API.
Retrofit retrofit = newRetrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
3. 創建接口請求實例
// Create an instance of our GitHub API interface.
GitHub github =retrofit.create(GitHub.class);
// Create a call instancefor looking up Retrofit contributors.
Call<List<Contributor>> call =github.contributors("square", "retrofit");
4. 獲取數據,分同步請求和異步請求
同步請求
1 2 3 4 |
// Synchronous Call in Retrofit 2.0
List<Contributor> contributors = call.execute().body(); |
以上的代碼會阻塞線程,因此你不能在安卓的主線程中調用,不然會面臨NetworkOnMainThreadException。如果你想調用execute方法,請在後臺線程執行。
異步請求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Synchronous Call in Retrofit 2.0
call.enqueue(List<Contributor> () { @Override public void onResponse(Response List<Contributor> response) { // Get result Repo from response.body() }
@Override public void onFailure(Throwable t) {
} }); |
以上代碼發起了一個在後臺線程的請求並從response 的response.body()方法中獲取一個結果對象。注意這裏的onResponse和onFailure方法是在主線程中調用的。
5.
demo地址 |