Retrofit是一個resful形式的網(wǎng)絡(luò)請求框架,它是基于okhttp網(wǎng)絡(luò)請求SDK的二次封裝。參考文檔:http://www.itdecent.cn/p/308f3c54abdd
使用框架需要引入的包庫
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0' compile '
com.squareup.retrofit2:converter-gson:2.3.0'
第一步:我們定義一個接受返回信息的Bean:InfoBean包含三個字段 code、reason、result。視返回的json數(shù)據(jù)的字典而定,保持一致方可
第二步:使用retrofit需要定義請求接口
public interface BlogService {
@GET("blog/{id}")
Call<ResponseBody> getBlog(@Path("id") int id);
}
其中的Call留意一下
第三步:使用代理模式申明對象才能調(diào)用接口方法
BlogService service = retrofit.create(BlogService.class);
第四步:異步請求
Call<ResponseBody> call = service.getBlog(2);
// 用法和OkHttp的call如出一轍,
// 不同的是如果是Android系統(tǒng)回調(diào)方法執(zhí)行在主線程
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) { e.printStackTrace(); } }
@Override public void onFailure(Call<ResponseBody> call, Throwable t)
{
t.printStackTrace();
}
});
學(xué)會初步使用可以了解更詳細(xì)的注解及配合rxjava使用