Retrofit2.0使用
來自: http://blog.csdn.net/qq_17766199/article/details/49946429
Retrofit項目Github主頁:點擊打開鏈接
Retrofit項目官方文檔 :點擊打開鏈接
首先是我參考的文章:
● Retrofit 2.0使用詳解,配合OkHttp、Gson,Android最強網絡請求框架
這里感謝以上的作者對于 Retrofit使用的講解,對我的幫助很大。
那么我根據自己的使用情況做一下匯總:因為也是第一次使用,沒有接觸過2.0之前的版本,所以不介紹與舊版區別。
(1)權限:首先確保在AndroidManifest.xml中請求了網絡權限 :
<uses-permission android:name="android.permission.INTERNET" />
(2)Studio用戶,在app/build.gradle文件中添加如下代碼:
dependencies {
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.okio:okio:1.6.0'
} Eclipse的用戶,可以下載最新的jar:我將整理的jar包已上傳:點擊打開鏈接
注意:1.Retrofit必須使用okhttp請求了,如果項目中沒有okhttp的依賴的話,肯定會出錯 。
2.okhttp內部依賴okio所以也要添加。
2.使用
(1)創建Retrofit實例
public static final String BASE_URL = "http://api.myservice.com";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.build(); 如果你想接收json 結果并解析成DAO,你必須把Gson Converter 作為一個獨立的依賴添加進來。
compile 'com.google.code.gson:gson:2.4' compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
這里是Square提供的官方Converter modules列表。選擇一個最滿足你需求的。
Gson: com.squareup.retrofit:converter-gson
Jackson: com.squareup.retrofit:converter-jackson
Moshi: com.squareup.retrofit:converter-moshi
Protobuf: com.squareup.retrofit:converter-protobuf
Wire: com.squareup.retrofit:converter-wire
Simple XML: com.squareup.retrofit:converter-simplexml
你也可以通過實現Converter.Factoty接口來創建一個自定義的converter。
然后使用addConverterFactory把它添加進來:
public static final String BASE_URL = "http://api.myservice.com";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build(); (2)定義Endpoints,實現了轉換HTTP API為Java接口
Retrofit提供了5種內置的注解:GET、POST、PUT、DELETE和HEAD,在注解中指定的資源的相對URL
@GET("users/list") 也可以在URL中指定查詢參數
@GET("users/list?sort=desc") 請求的URL可以在函數中使用替換塊和參數進行動態更新,替換塊是{ and }包圍的字母數字組成的字符串,相應的參數必須使用相同的字符串被@Path進行注釋
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId); 也可以添加查詢參數
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort); 復雜的查詢參數可以使用Map進行組合
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options); 可以通過@Body注解指定一個對象作為Http請求的請求體
@POST("users/new")
Call<User> createUser(@Body User user); 使用@FormUrlEncoded發送表單數據,使用@Field注解和參數來指定每個表單項的Key,Value為參數的值。
@FormUrlEncoded
@POST("user/edit")
Call<User> getUser(@Field("name") String name, @Field("password") String password);
使用@FormUrlEncoded發送表單數據時,表單項過多時可以使用Map進行組合
@FormUrlEncoded
@POST("user/edit")
Call<User> getUser(@FieldMap Map<String, String> map); 使用@Multipart可以進行文件上傳,使用@Part指定文件路徑及類型
@Multipart
@POST("/user/edit")
Call<User> upload(@Part("image\"; filename=\"文件名.jpg") RequestBody file); 使用@MapPart可以方便批量上傳
@Multipart
@POST("/user/edit")
Call<User> upload(@PartMap Map<String, RequestBody> params); RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), imgFile);
map.put("image\"; filename=\""+imgFile.getName()+"", fileBody); (3)Accessing the API
public interface MyApiEndpointInterface {
// Request method and URL specified in the annotation
// Callback for the parsed response is the last parameter
@GET("/users/{username}")
Call<User> getUser(@Path("username") String username);
}
MyApiEndpointInterface apiService = retrofit.create(MyApiEndpointInterface.class);
異步請求這個API
String username = "sarahjean";
Call<User> call = apiService.getUser(username);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response) {
int statusCode = response.code();
User user = response.body();
}
@Override
public void onFailure(Throwable t) {
// Log error here since request failed
}
}); 同步請求
String username = "sarahjean"; Call<User> call = apiService.getUser(username); User user = call.execute();
3.注意
(1)我們在同步方法使用時可以直接調用execute方法,但是這個方法只能調用一次。解決辦法:需要用clone方法生成一個新的之后在調用execute方法:
Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
response = call.execute();
// This will throw IllegalStateException:
response = call.execute();
Call<List<Contributor>> call2 = call.clone();
// This will not throw:
response = call2.execute(); (2)當我們執行的同步或異步加入隊列后,可以隨時使用cancel方法取消請求:
Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
call.enqueue(...);
// or...
call.execute();
// later...
call.cancel();