您的位置:首页 > 移动开发 > Android开发

Android学习和使用Retrofit框架

2017-03-01 08:49 134 查看
最近,有一款网络请求框架很火,那就是Retrofit框架(基于okhttp)。

首先,我们来看下我们在build.gradle中需要依赖的远端jar包

//retrofit框架
compile "com.squareup.retrofit2:retrofit:2.1.0"
compile "com.squareup.retrofit2:converter-gson:2.1.0"
compile "com.squareup.retrofit2:adapter-rxjava:2.1.0"
compile "com.squareup.okhttp3:logging-interceptor:3.4.1"
由于要做api开发,我们可以利用阿里云的免费数据~~(有好资源就要利用啊)



我们先新建个bean---Weather

public class Weather implements Serializable{
private String status;
private String msg;
private List<ResultBean> result;

public List<ResultBean> getResult() {
return result;
}

public void setResult(List<ResultBean> result) {
this.result = result;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public class ResultBean{
private String cityid;
private String parentid;
private String citycode;
private String city;

public String getCityid() {
return cityid;
}

public void setCityid(String cityid) {
this.cityid = cityid;
}

public String getParentid() {
return parentid;
}

public void setParentid(String parentid) {
this.parentid = parentid;
}

public String getCitycode() {
return citycode;
}

public void setCitycode(String citycode) {
this.citycode = citycode;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}

}
这里我是利用mvp+rxjava+retrofit+dagger2的开发

利用OOP,我们把要请求的接口封装起来 定义一个请求接口 ApiService

public interface ApiService {
//网络请求方法
@Headers("Autho
aa66
rization:APPCODE 你的appcode")
@GET("/weather/city")
Observable<List<Weather>> listRepos();
}

对接口实现(做具体的事情,我这里只是抽离出来)

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://jisutqybmf.market.alicloudapi.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService weatherService = retrofit.create(ApiService.class);
weatherService.listRepos().enqueue(new Callback<Weather>() {
@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {
Log.d("", "onResponse: " + response);
response.body().getResult();
return;
}

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

}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: