目录
案例下载传送门
主页
中文资料
用途
- 效率非常高
- 可以直接将结果转换成Java类
- 结合RxJava使用简直起飞
注意
- 使用Retrofit的前提是服务器端代码遵循REST规范 !!!
- Retrofit requires at minimum Java 7 or Android 2.3.
基本概念
常用注解:
####请求方法类,分别对应 HTTP 的请求方法;
@Get / @POST / @PUT / @DELETE / @PATCH / @HEAD / @OPTIONS
URL处理:
@Path - 参数替换 - http:
@GET("/group/{id}/users")
public Call<List<User>> groupList(@Path("id") int groupId);
@Query - 添加查询参数 - http:
?sort="传进来的sort"
@GET("/group/{id}/users")
public Call<List<User>> groupList(@Path("id") int groupId, @Query ("sort") String sort);
@QueryMap - 多个查询参数,封装到Map中
@GET("/group/{id}/users")
public Call<List<User>> groupList(@QueryMap Map<String ,String > options);
使用步骤
1. 添加依赖
1. 在com.android.tools.build:gradle 3.0 以上版本依赖在gradle 中的声明写法
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
2. 在com.android.tools.build:gradle 3.0 以下版本依赖在gradle 中的声明写法
例子:compile 'com.squareup.retrofit2:retrofit:2.4.0'
2. 创建数据模型
AS中有GsonFormat插件可以帮助解析
在线生成工具:https:
3. 网络权限
<uses-permission android:name="android.permission.INTERNET" />
4. 创建REST API接口
/**
* 测试接口使用的是聚合数据提供的免费API,自行申请将KEY替换
* 地址:https://www.juhe.cn/
*/
public interface ApiService {
String BASE_URL = "http://v.juhe.cn";
String KEY = "bc8a753f7********bedeb73ad18";
/**
* 接口1:获取天气信息, API一定是以 "/" 开头,这是Retrofit规范
*/
@GET("/weather/index")
Call<Weather> getWeather(@QueryMap Map<String, String> options);
}
5. 构建Retrofit
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btnRqt;
private TextView tvMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMsg = findViewById(R.id.tv_msg);
btnRqt = findViewById(R.id.btn_rqt);
btnRqt.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_rqt:
/**
* 构建Retrofit
*/
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
/**
* 构建接口实例
*/
ApiService weatherAPI = retrofit.create(ApiService.class);
Map<String ,String > map = new HashMap();
map.put("cityname" , "北京");
map.put("key" , ApiService.KEY);
Call<Weather> call = weatherAPI.getWeather(map);
call.enqueue(new Callback<Weather>() {
@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {
Weather body = response.body();
tvMsg.setText(body.getResult().getToday().getDressing_advice());
tvMsg.setTextColor(getResources().getColor(R.color.colorPrimary));
}
@Override
public void onFailure(Call<Weather> call, Throwable t) {
tvMsg.setText(t.getMessage());
tvMsg.setTextColor(getResources().getColor(R.color.colorAccent));
}
});
break;
}
}
}
案例下载传送门