Retrofit與Okhttp共同出自于Square公司,Retrofit就是對(duì)Okhttp做了一層封裝,我們只需要通過簡(jiǎn)單的配置就能使用進(jìn)行網(wǎng)絡(luò)請(qǐng)求了,其主要作者是Android大神Jake Wharton。廢話我就不多說了趣兄,直接上干貨,來來悼嫉,上車吧艇潭!
Retrofit2.0基本用法
1.Stuidio導(dǎo)入依賴
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
2.定義接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
3.獲取實(shí)例
Retrofit retrofit = new Retrofit.Builder()
//設(shè)置OKHttpClient,如果不設(shè)置會(huì)提供一個(gè)默認(rèn)的
.client(new OkHttpClient())
//設(shè)置baseUrl
.baseUrl("https://api.github.com/")
//添加Gson轉(zhuǎn)換器
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
4.請(qǐng)求數(shù)據(jù)
-
同步請(qǐng)求
Call<List<Repo>> call = service.listRepos("octocat");
try {
Response<List<Repo>> repos = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
//call只能調(diào)用一次。否則會(huì)拋 IllegalStateException
Call<List<Repo>> clone = call.clone();
-
異步請(qǐng)求
clone.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
// Get result bean from response.body()
List<Repo> repos = response.body();
// Get header item from response
String links = response.headers().get("Link");
/**
* 不同于retrofit1 可以同時(shí)操作序列化數(shù)據(jù)javabean和header
*/
}
@Override
public void onFailure(Call<List<Repo>> call, Throwable t) {
}
});
// 取消
call.cancel();
基本用法就完事了戏蔑,就是這么簡(jiǎn)單蹋凝!驚不驚喜?意不意外辛臊?
下面稍微說明一下相關(guān)注意的要點(diǎn):
retrofit注解:
方法注解仙粱,包含@GET、@POST彻舰、@PUT、@DELETE候味、@PATH刃唤、@HEAD、@OPTIONS白群、@HTTP尚胞。
標(biāo)記注解,包含@FormUrlEncoded帜慢、@Multipart笼裳、@Streaming。
參數(shù)注解粱玲,包含@Path躬柬,@Query,@QueryMap、@Body抽减、@Field允青,@FieldMap、@Part卵沉,@PartMap颠锉。
其他注解@Url:一般用于完整的url
@HTTP:可以替代其他方法的任意一
* method 表示請(qǐng)的方法,不區(qū)分大小寫
* path表示路徑
* hasBody表示是否有請(qǐng)求體
*/
@HTTP(method = "get", path = "users/{user}", hasBody = false)
Call<ResponseBody> getFirstBlog(@Path("user") String user);
@Url:使用全路徑復(fù)寫baseUrl史汗,適用于非統(tǒng)一baseUrl的場(chǎng)景琼掠。
@GET
Call<ResponseBody> v3(@Url String url);
@Streaming:用于下載大文件
@Streaming
@GET
Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);
ResponseBody body = response.body();
long fileSize = body.contentLength();
InputStream inputStream = body.byteStream();
@Path:URL占位符,用于替換和動(dòng)態(tài)更新,相應(yīng)的參數(shù)必須使用相同的字符串被@Path進(jìn)行注釋
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
//--> http://baseurl/group/groupId/users
//等同于:
@GET
Call<List<User>> groupListUrl(
@Url String url);
@Query,@QueryMap:查詢參數(shù)停撞,用于GET查詢,需要注意的是@QueryMap可以約定是否需要encode
@GET("group/users")
Call<List<User>> groupList(@Query("id") int groupId);
//--> http://baseurl/group/users?id=groupId
Call<List<News>> getNews((@QueryMap(encoded=true) Map<String, String> options);
@Body:用于POST請(qǐng)求體瓷蛙,將實(shí)例對(duì)象根據(jù)轉(zhuǎn)換方式轉(zhuǎn)換為對(duì)應(yīng)的json字符串參數(shù),這個(gè)轉(zhuǎn)化方式是GsonConverterFactory定義的。
@POST("add")
Call<List<User>> addUser(@Body User user);
@Field速挑,@FieldMap:Post方式傳遞簡(jiǎn)單的鍵值對(duì),需要添加@FormUrlEncoded表示表單提交
Content-Type:application/x-www-form-urlencoded
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
@Part谤牡,@PartMap:用于POST文件上傳
其中@Part MultipartBody.Part代表文件,@Part("key") RequestBody代表參數(shù)
需要添加@Multipart表示支持文件上傳的表單姥宝,Content-Type: multipart/form-data
@Multipart
@POST("upload")
Call<ResponseBody> upload(@Part("description") RequestBody description,
@Part MultipartBody.Part file);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
@Header:header處理翅萤,不能被互相覆蓋,用于修飾參數(shù)腊满,
//動(dòng)態(tài)設(shè)置Header值
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
等同于 :
//靜態(tài)設(shè)置Header值
@Headers("Authorization: authorization")//這里authorization就是上面方法里傳進(jìn)來變量的值
@GET("widget/list")
Call<User> getUser()
@Headers 用于修飾方法,用于設(shè)置多個(gè)Header值:
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
好了關(guān)于Retrofit的用法今天就介紹到這里套么,我們下篇繼續(xù)約,不見不散