retrofit入门 简单使用
retrofit出来也不久了,这篇就写一下它的入门简单的使用:下篇会跟上retrofit和rxjava的配合使用:
首先需要依赖:
compile
'com.squareup.okhttp3:okhttp:3.9.0'
compile
'com.squareup.retrofit2:retrofit:2.0.1'
compile
'com.google.code.gson:gson:2.3'
compile
'com.squareup.retrofit2:converter-gson:2.0.0'
其次是接口:
public interface INRetrofit { @GET("api/xxx/xxx/{page}") Call<Result> getResult(@Path("page") int apikey); }实体类:
public class Result { private int code; private String msg; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { private List<SortBean> sort; private List<?> goods; public List<SortBean> getSort() { return sort; } public void setSort(List<SortBean> sort) { this.sort = sort; } public List<?> getGoods() { return goods; } public void setGoods(List<?> goods) { this.goods = goods; } public static class SortBean { /** * id : 1 * name : 水机专区 * addtime : 2017-09-21 13:59:35 */ private int id; private String name; private String addtime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddtime() { return addtime; } public void setAddtime(String addtime) { this.addtime = addtime; } } } }
最后是用法:
/** * retrofit测试 */ private void retrofitTest() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://xxx.xxxxx.xxx/index.php/") .addConverterFactory(GsonConverterFactory.create(new Gson())) .build(); INRetrofit repo = retrofit.create(INRetrofit.class); retrofit2.Call<Result> responseBodyCall = repo.getResult(100); responseBodyCall.enqueue(new retrofit2.Callback<Result>() { @Override public void onResponse(retrofit2.Call<Result> call, retrofit2.Response<Result> response) { try { Result body = response.body(); /** * 在这里处理就可以了 */ } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(retrofit2.Call<Result> call, Throwable t) { } }); }
紫色代码部分官网并没有说道,所以你可能会报Could not locate ResponseBody converter for class com.example.administrator xxxx的错误哦,
添加上紫色代码,声明下是gson格式就好啦。
蛮简单的哦!