一:Retrofit用法
支持基本的HTTP請(qǐng)求
主要用法:
(1)一般的Get請(qǐng)求
public interface IUserBiz
{
@GET("users")
Call<List<User>> getUsers();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.31.242:8080/springmvc_users/user/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IUserBiz userBiz = retrofit.create(IUserBiz.class);
Call<List<User>> call = userBiz.getUsers();
call.enqueue(new Callback<List<User>>()
{
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response)
{
Log.e(TAG, "normalGet:" + response.body() + "");
}
@Override
public void onFailure(Call<List<User>> call, Throwable t)
{
}
});
(2)動(dòng)態(tài)Url訪問(@Path)
/用于訪問zhy的信息
http://192.168.1.102:8080/springmvc_users/user/zhy
//用于訪問lmj的信息
http://192.168.1.102:8080/springmvc_users/user/lmj
public interface IUserBiz
{
@GET("{username}")
Call<User> getUser(@Path("username") String username);
}
//省略了retrofit的構(gòu)建代碼
Call<User> call = userBiz.getUser("zhy");
//Call<User> call = userBiz.getUser("lmj");
call.enqueue(new Callback<User>()
{
@Override
public void onResponse(Call<User> call, Response<User> response)
{
Log.e(TAG, "getUsePath:" + response.body());
}
@Override
public void onFailure(Call<User> call, Throwable t)
{
}
});
(3)查詢參數(shù)設(shè)置(@Query)
http://baseurl/users?sortby=username
http://baseurl/users?sortby=id
public interface IUserBiz
{
@GET("users")
Call<List<User>> getUsersBySort(@Query("sortby") String sort);
}
//省略retrofit的構(gòu)建代碼
Call<List<User>> call = userBiz.getUsersBySort("username");
//Call<List<User>> call = userBiz.getUsersBySort("id");
//省略call執(zhí)行相關(guān)代碼
(4)Post請(qǐng)求體的方式向服務(wù)器提交Json字符串(@Body)
public interface IUserBiz
{
@POST("add")
Call<List<User>> addUser(@Body User user);
}
//省略retrofit的構(gòu)建代碼
Call<List<User>> call = userBiz.addUser(new User(1001, "jj", "123,", "jj123", "jj@qq.com"));
//省略call執(zhí)行相關(guān)代碼
(5)表單的方式傳遞鍵值對(duì)FormUrlEncoded
public interface IUserBiz
{
@POST("login")
@FormUrlEncoded
Call<User> login(@Field("username") String username, @Field("password") String password);
}
//省略retrofit的構(gòu)建代碼
Call<User> call = userBiz.login("zhy", "123");
//省略call執(zhí)行相關(guān)代碼
(6)單文件上傳(@Multipart)
public interface IUserBiz
{
@Multipart
@POST("register")
Call<User> registerUser(@Part MultipartBody.Part photo, @Part("username") RequestBody username, @Part("password") RequestBody password);
}
File file = new File(Environment.getExternalStorageDirectory(), "icon.png");
RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("photos", "icon.png", photoRequestBody);
Call<User> call = userBiz.registerUser(photo, RequestBody.create(null, "abc"), RequestBody.create(null, "123"));
(7)多文件上傳(@PartMap)
public interface IUserBiz
{
@Multipart
@POST("register")
Call<User> registerUser(@PartMap Map<String, RequestBody> params, @Part("password") RequestBody password);
}
File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png");
RequestBody photo = RequestBody.create(MediaType.parse("image/png", file);
Map<String,RequestBody> photos = new HashMap<>();
photos.put("photos\"; filename=\"icon.png", photo);
photos.put("username", RequestBody.create(null, "abc"));
Call<User> call = userBiz.registerUser(photos, RequestBody.create(null, "123"));
(8)下載文件(@Get("download"))
缺點(diǎn): 并且onReponse回調(diào)雖然在UI線程翼馆,但是你還是要處理io操作,也就是說你在這里還要另外開線程操作憔鬼,或者你可以考慮同步的方式下載。
@GET("download")
Call<ResponseBody> downloadTest();
Call<ResponseBody> call = userBiz.downloadTest();
call.enqueue(new Callback<ResponseBody>()
{
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
{
InputStream is = response.body().byteStream();
//save file
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
}
});
二:retrofit 源碼解析
1 首先構(gòu)造retrofit,幾個(gè)核心的參數(shù)呢炮叶,主要就是baseurl,callFactory(默認(rèn)okhttpclient),converterFactories,adapterFactories,excallbackExecutor术辐。
2 然后通過create方法拿到接口的實(shí)現(xiàn)類,這里利用Java的Proxy類完成動(dòng)態(tài)代理的相關(guān)代理
3 在invoke方法內(nèi)部拆撼,拿到我們所聲明的注解以及實(shí)參等容劳,構(gòu)造ServiceMethod,ServiceMethod中解析了大量的信息闸度,最痛可以通過toRequest構(gòu)造出okhttp3.Request對(duì)象竭贩。有了okhttp3.Request對(duì)象就可以很自然的構(gòu)建出okhttp3.call,最后calladapter對(duì)Call進(jìn)行裝飾返回莺禁。
4 拿到Call就可以執(zhí)行enqueue或者execute方法了留量。