Android开发Android开发经验谈Android技术知识

Retrofit实战笔记 | 简析官方API文档(结合示例代码)

2019-06-08  本文已影响9人  凌川江雪

官方文档简阅

@GET("user/{id}")
    Call<User> getUserInfoWithPath(@Path("id") int user_id);

<List<Repo>>对应的位置类型就是User
所以上面这个Call方法 返回的就是一个User类型的实例
所以省去了我们用Gson解析的步骤:

private Api api;
---
User user = api.getUserInfoWithPath(1).execute().body();



以上可以归结为三个步骤,示例代码如下:

//1. 定义对应 HTTP API的 Java接口
public interface Api {
    @GET("user/{id}")
    Call<User> getUserInfoWithPath(@Path("id") int user_id);
}

---
private Api api;

---
//2. 创建 Retrofit实例,通过该实例创建接口代理实例
      Retrofit retrofit = new Retrofit.Builder()
              .baseUrl("http://192.168.1.189:5000/")
              .addConverterFactory(GsonConverterFactory.create())
              .build();

      api = retrofit.create(Api.class);

---
//3. 通过接口代理实例调用自定义的请求方法,得到返回结果
User user = api.getUserInfoWithPath(1).execute().body();

其他API文档






参考自 菜鸟窝

上一篇 下一篇

猜你喜欢

热点阅读