Retrofit-基本使用

前言
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)
            }
        });
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值