//导依赖
//Retrofit2的依赖
compile ‘com.squareup.retrofit2:converter-gson:2.0.0-beta4’
//接口单写一个类便于更改
public class Constant {
//网址
public final static String URL_BASE = "http://www.xieast.com/";
}
//Retrofilt接口里拼接网址
public interface MyDoGet {
///
// GET网络请求方式
///
/**Get请求,方法中无参数
* 作用:GET请求最简单的写法,无Path参数和Query参数
* article/list/latest?page=%d实际是Constant下的URL_LATEST地址
* @GET()里的东西是要拼接的网址,注意直接把page=1了
*/
@GET("article/list/latest?page=1")
Call<ResponseBody> getLatestJsonString();
}
//mainActivity逻辑的实现
public class MainActivity extends AppCompatActivity {
private TextView tv_info;
private Call<ResponseBody> call;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
//初始化Retrofit
initRetrofit();
}
private MyDoGet mMyDoGet = null;
//初始化Retrofilt
private void initRetrofit() {
//创建Retrofilt对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL_BASE)
.build();
//创建接口对象,参数:接口的字节码
mMyDoGet = retrofit.create(MyDoGet.class);
//类似okhttp,通过接口对象,调用抽象方法,创建出call对象
call = mMyDoGet.getLatestJsonString();
call.enqueue(new Callback() {
//请求成功的回调(Retrofit与okhttp不同,回调方法是运行在主线程而不 是子线程的)
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccess() && response.body() != null) {
try {
//得到结果
String s = response.body().string();
//更新UI
tv_info.setText(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
//请求失败的回调
private void initView() {
tv_info = (TextView) findViewById(R.id.tv_info);
}
//为节约资源,当屏幕不可见时,我们停止网络请求
@Override
protected void onStop() {
super.onStop();
if (mCall != null) {
mCall.cancel();
}
}