前言
Retrofit 是 Square 公司出品的 HTTP 请求库;官方的介绍:A type-safe HTTP client for Android and Java。
Retrofit是一套RESTful架构的Android(Java)客户端实现,基于注解,提供JSON to POJO(Plain Ordinary Java Object,简单Java对象),POJO to JSON,网络请求(POST,GET,PUT,DELETE等)封装。
基本使用
Github链接:
https://github.com/square/retrofit
引入依赖
compile ‘com.squareup.retrofit2:retrofit:2.0.2’
下面的实例是获取城市的天气,以北京为例,url地址为:http://www.weather.com.cn/data/sk/101010100.html
1、定义POJO或模型实体类
从服务器获取的JSON数据将被填充到这种类的实例中。
public class WeatherinfoResult {
private Weatherinfo weatherinfo;
public Weatherinfo getWeatherinfo() {
return weatherinfo;
}
public void setWeatherinfo(Weatherinfo weatherinfo) {
this.weatherinfo = weatherinfo;
}
}
//
public class Weatherinfo {
private String city;
private String cityid;
private String temp;
private String WD;
private String WS;
private String SD;
private String WSE;
private String time;
private String isRadar;
private String Radar;
private String qy;
private String rain;
//省略了setter getter相关方法
}
2、定义请求接口
该接口定义了一个函数 getWearther(),该函数会通过HTTP GET(通过@GET方式注解实现)请求去访问服务器的BASE_URL/{city} 路径并把返回的结果封装为 WeatherinfoResult对象返回。
其中URL路径中的 { city } 的值为 getWearther()函数中的参数 city的取值。
/**
* 首先定义请求接口,即需要请求的操作
*/
public interface IWeatherService {
@GET("{city}")
Call<WeatherinfoResult> getWearther(@Path("city") String city);
}
3、 实现Retrofit调用
private void loadWeather() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.weather.com.cn/data/sk/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IWeatherService weatherService = retrofit.create(IWeatherService.class);
Call<WeatherinfoResult> repos = weatherService.getWearther("101010100.html");
repos.enqueue(new Callback<WeatherinfoResult>() {
@Override
public void onResponse(Call<WeatherinfoResult> call, Response<WeatherinfoResult> response) {
Log.v(TAG, "weatherInfo=" + response.body().getWeatherinfo())
}
@Override
public void onFailure(Call<WeatherinfoResult> call, Throwable t) {
Log.v(TAG, "error=" + t)
}
});
}