美文网首页
Retrofit2.1.0深入学习@GET【第一章】

Retrofit2.1.0深入学习@GET【第一章】

作者: Small_Cake | 来源:发表于2016-09-07 15:54 被阅读178次

GitHub地址:Retrofit2.1.0

Gradle引用:compile'com.squareup.retrofit2:retrofit:2.1.0'

1.Retrofit可以直接返回【对象类型】,所以我们要引入Google的Gson和对应的转换器

compile'com.google.code.gson:gson:2.5'
compile'com.squareup.retrofit2:converter-gson:2.1.0'

2.Retrofit有时需要直接返回【String】,需要引入

compile'com.squareup.retrofit2:converter-scalars:2.1.0'

3.Retrofit常用的类型返回【JSONObject】,retrofit2源码里面没有,不知道为什么,只有自己写相应的转换类,当然是GitHub上面找的,然后下载下来添加到项目中:JSONCoverter

最后如果Retrofit在构建的时候没有加入转换器,默认返回【RequestBody】
引入相关库和代码后,我们写自己的网络请求工具了,以查询天气为例:

public class WeatherRetrofit {
interface WeatherInteface {
//如果这里的域名和key都是不变的,可以写在单独的一个数据管理接口中
String JUHE_WEATHER_KEY="11c39e939a9a32caa5613f9d0e3cf598";
String HOST="http://op.juhe.cn/onebox/weather/";
//这里就写查询各种方法,例如查返回json格式的方法
@GET("query?key="+JUHE_WEATHER_KEY)
Call getJSONObject(@Query("cityname") String cityname);
//@GET("{query}?key=" + JUHE_WEATHER_KEY)
//Call<JSONObject> getJSONObject(@Path("query") String path,@Query("cityname") String cityname);
}
public static voiddoGet(String city, Callback callback) {
//1.在构建Retrofit的时候,就把域名host设定好了,并通过addConverterFactory来转换返回的数据类型,这里使用json
Retrofit build =newRetrofit.Builder().baseUrl(WeatherInteface.HOST).addConverterFactory(JsonConverterFactory.create()).build();
//2.创建接口实例,传入上面的接口
WeatherInteface inteface = build.create(WeatherInteface.class);
//3.最后通过接口方法传入city参数,并调用enqueue传入callback回调,开始真正的查询
inteface.getJSONObject(city).enqueue(callback);
//inteface.getJSONObject("query",city).enqueue(callback);
}
}
  • 上面代码中的@GET就是发起的GET请求,里面传入了地址和一个key的参数,同时在方法中也可以通过@Query()来传入参数
  • 有的时候我们的请求二级地址也是动态改变的,那么只要在@GET中给改变部分加大括号,然后参数里面写地址就可以了
    使用也非常简单,在要查询数据的地方直接通过该类的方法查询
WeatherRetrofit.doGet("北京", new Callback() {    
 @Override    
public void onResponse(Call call, Response response) {   
L.i("---"+response.body());   
tvMsg.setText(response.body().toString());    
}    
@Override    
public void onFailure(Call call, Throwable t) {        
L.e("---"+t.getMessage());    
}
});```

![Paste_Image.png](https://img.haomeiwen.com/i1503465/9099ec793c0e2dab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

相关文章

网友评论

      本文标题:Retrofit2.1.0深入学习@GET【第一章】

      本文链接:https://www.haomeiwen.com/subject/yxbjettx.html