本人也是菜鸟一枚。。在了解Rxjava的时候偶然看到了Retrofit这个框架(其实应该可以算是必然吧,因为几乎每一篇介绍Rx的文章都会提到Retrofit),这个框架目前已经升级到2.0了,跟1.9之前的版本有很大区别,下来来介绍一下最基本的用法
有一个小细节:目前Retrofit有两个版本,Retrofit 和 Retrofit2这两个版本的参数是不通用的
话不多说,来开始一个Get请求。先声明一个接口,也有叫Service的,大家知道就好。。
完整的接口如下:
http://apistore.baidu.com/microservice/cityinfo?cityname=北京
这是一个查询城市代码的接口。。
public interface GetCityCode{
@GET("/microservice/cityinfo")
//CityCodeBean是根据接口返回数据生成的一个类,这个类包含了该城市的一些信息
Call<CityCodeBean> getWeather(@Query("cityname")String cityname);
}
//初始化一个Retrofit
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://apistore.baidu.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
//得到一个接口对象。。别问怎么得到的,,我也不知道。。
GetCityCode code=retrofit.create(GetCityCode.class);
Call<CityCodeBean> call=code.getWeather("北京");
//开始异步请求。。
call.enqueue(new Callback<CityCodeBean>() {
@Override
public void onResponse(Response<CityCodeBean> response) {
//response.body()就是指定的类,,这里是CityCodeBean
Log.e("北京Get",response.body().getRetMsg());
}
@Override
public void onFailure(Throwable t) {
}
});
//什么?你想做同步请求?不堵死人誓不休?。。好吧,同步是这样请求的:友情提示这个方法是会堵塞UI线程的。。
//PS:call是不能重复用的,必须重新获取
Call<CityCodeBean> call2=code.getWeather("北京");
try {
CityCodeBean cityCodeBean=call2.execute().body();
Log.e("同步",cityCodeBean.getRetMsg());
} catch (IOException e) {
Log.e("error",e.getMessage());
e.printStackTrace();
}
然而,老夫只想悄悄地post一下怎么破。。注意我要发大招了。。
public interface PostCityCode{
@POST("/microservice/cityinfo")
//请注意这里是一个map
Call<CityCodeBean> getWeatherByPost(@QueryMap Map<String,String> map);
}
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://apistore.baidu.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
PostCityCode code=retrofit.create(PostCityCode.class);
Map<String,String> map=new HashMap<>();
map.put("cityname","北京");
Call<CityCodeBean> post=code.getWeatherByPost(map);
//以下雷同
call.enqueue(new Callback<CityCodeBean>() {
@Override
public void onResponse(Response<CityCodeBean> response) {
Log.e("北京Post",response.body().getRetMsg());
}
@Override
public void onFailure(Throwable t) {
}
});
此外1.9及以前的版本应该是没有Retrofit的,代替的功能类应该是RestAdapter,之所以写这个是因为刚接触Retrofit的时候正是2.0与1.X旧版本迭代的时候,网上有很多教程都是1.x的。。自己也花了一点时间摸索了一下才成功地进行了请求,就写下来当做笔记吧!