Retrofit基础之最简单的get请求方式

Retrofit基础之最简单的get请求方式

标签:网络框架


添加依赖

compile 'com.squareup.retrofit2:retrofit:2.x.x'
compile 'com.squareup.retrofit2:converter-gson:2.x.x'       //这个也必须加进去,这是一坑

用法

  • 本例子以聚合数据天气预报API接口测试。
  • 接口基地址为:(http://v.juhe.cn/weather/)而根据城市名/id查询天气是在基地址后面加一段(index)
  • 代码中 WeatherResp 为数据结构原型,根据自己的数据体建一个Bean放进去就OK了

1、首先先建一个接口,可以理解为URL自由拼接的接口

public interface WeatherService {
    //@GET会被识别为get请求
    //index会拼接到BASE_URL中,此时这个URL已经拼接完毕
    @GET("index")       //@Query会被识别为往完整URL中附带参数(index?key=xxx&cityname=xx&···)
    Call<WeatherResp> cityNameQueryWeather(@Query("key") String key,
                                           @Query("cityname") String cityname,
                                           @Query("format") int format); //format是非必要参数,可以用重写
}

2、再建一个类,将基本的进行封装,如不需要用户输入的KEY

//根据城市名查询天气
public class HttpModel {
                              //接口地址相同的部分抽取出来作为BASE_URL
    private static final String BASE_URL = "http://v.juhe.cn/weather/";
                              //聚合平台分配的key,抽取出来
    private static final String KEY = "------------------------";
                      //实例化一个gson
    private static Gson gson = new Gson();

                      //针对部分不需要用户输入的参数进行内部自行解决,如key
    public static Call<WeatherResp> cityNameToQuery(String cityName, int format) {
        //通过建造者模式  Builder链式构造出Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                //首先设置BASE_URL,会与index进行拼接URL
                .baseUrl(BASE_URL)
                /*这个非常重要,官方说默认是gson,我当时以为不用写这个,结果一直报错
                 *所以还是要写,这个时候用的就是依赖的第二个包
                 */
                .addConverterFactory(GsonConverterFactory.create(gson))
                //然后通过build构建完成,此时就是一个Retrofit实例
                .build();
        //然后通过Retrofit实例creat出WeatherService接口实例。
        WeatherService service = retrofit.create(WeatherService.class);
        //拿到接口实例,去调用接口内的方法,返回值是一个回调接口Call
        Call<WeatherResp> call = service.cityNameQueryWeather(KEY, cityName, format);
        //将回调接口Call返回出去
        return call;
    }
                      //针对上面的方法重写变为一个参数,format平台默认为1,也可以忽略用户未输入
    public static Call<WeatherResp> cityNameToQuery(String cityName) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        WeatherService service = retrofit.create(WeatherService.class);
        Call<WeatherResp> call = service.cityNameQueryWeather(KEY, cityName, 1);
        return call;
    }
}

3、开始请求数据

//在MainActivity中开始请求数据    //enqueue是异步请求方式,添加回调返回数据
HttpModel.cityNameToQuery("武汉").enqueue(new Callback<WeatherResp>() {
    @Override
    public void onResponse(Call<WeatherResp> call, Response<WeatherResp> response) {
        //response.body才是数据原型
        Log.d("body", response.body().toString());
    }

    @Override
    public void onFailure(Call<WeatherResp> call, Throwable t) {

    }
});

更方便写法

1、接口WeatherService

public interface WeatherService {
    @GET("index")
    Call<WeatherResp> cityNameQueryWeather(@Query("key") String key,
                                           @Query("cityname") String cityname,
                                           @Query("format") int format);

    public class BuildRetrofit {
        private static final String BASE_URL = "http://v.juhe.cn/weather/";
        private static Gson gson = new Gson();
        public static WeatherService retrofit() {
            WeatherService service = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build()        //实例化Retrofit   再去创建WeatherService实例
                    .create(WeatherService.class);
            return service;
        }
    }
}

2、封装类HttpModel

//根据城市名查询天气
public class HttpModel {
    private static final String KEY = "-----------------------";

    public static Call<WeatherResp> cityNameToQuery(String cityName, int format) {
        Call<WeatherResp> call = WeatherService.BuildRetrofit.retrofit().cityNameQueryWeather(KEY, cityName, format);
        return call;
    }

    public static Call<WeatherResp> cityNameToQuery(String cityName) {
        Call<WeatherResp> call = WeatherService.BuildRetrofit.retrofit().cityNameQueryWeather(KEY, cityName, 1);
        return call;
    }
}

3、开始请求网络

HttpModel.cityNameToQuery("武汉").enqueue(new Callback<WeatherResp>() {
    @Override
    public void onResponse(Call<WeatherResp> call, Response<WeatherResp> response) {
        Log.d("body", response.body().toString());
    }
    @Override
    public void onFailure(Call<WeatherResp> call, Throwable t) {
    }
});

结后语

  • 至此Retrofit最简单的GET请求就是这样了,相信大家能举一反三
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值