Retrofit GET请求方式的简单使用

Retrofit GET方式的简单使用
1.加入依赖
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
2.创建一个 net 包里面创建一个名为 constant 的类
这个类主要写的是接口地址
// 因为 retrofit使用的时候地址是要进行拼接 的所以在constant类中写 地址的时候应该写到 / 就可以
public final static String URL_PATH = "https://www.zhaoapi.cn/" ;
3.创建一个 connector 包,里面 要创建一个接口
在接口里面主要的操作 就是拼接constant中的另一半地址
使用注解的方法
@GET() (括号里面的参数就是地址剩下的部分)
定义一个call< ResponseBody >类型的数据
Call<ResponseBody> getDatas();

4.具体使用
1.创建retrofit对象
Retrofit retrofit= new Retrofit.Builder ()
//里面的参数就是Constant类中的变量,直接Constant.出来
.baseUrl (Constant. URL_PATH )
.build ();
2.创建接口对象
//创建接口对象 返回一个MyServerInterface类型 参数是 MyServerInterface定义的接口.class
serverInterface = retrofit.create (MyServerInterface. class );

//通过接口对象,调用抽象方法,创建call对象,类似于okhtttp,得到接口中的方法
Call<ResponseBody> mcall = serverInterface .getDatas ();
//请求数据
mCall.enqueue(new Callback<ResponseBody>() {
//请求成功的回调(Retrofit与okhttp不同,回调方法是运行在主线程而不是子线程的)
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//打一个log
Log.d(TAG, "---->threadId:" + Thread.currentThread().getId());
//对返回结果做成功与内容的判断
if (response.isSuccess() && response.body() != null) {
try {
//得到结果
String result = response.body().string();
//更新UI
textView_info.setText(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//请求失败的回调
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {}
});
3.关闭资源
//为节约资源,当屏幕不可见时,我们停止网络请求
@Override
protected void onStop() {
super.onStop();
if (mCall != null) {
mCall.cancel();
}
}

猜你喜欢

转载自blog.csdn.net/lxd13699/article/details/80665448