一:Retrofit,它是一个可以用于Android和java的网络库,使用它可以简化我们网络操作的工作,提高效率和正确率
模式:动态代理
优点 :请求到数据在主线程 可以省去切换到主线程
二:依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
三:使用
1:将Rest API转换为java接口
public interface RetrofitService {
@GET("product/getCatagory")
Call<Bean<List<DataBean>>> getservice();
@GET("user/getUserInfo")
Call<Bean<DataBean2>> get(@Query("uid") String uid);
/**
* method 表示请求的方法,区分大小写
* path表示路径
* hasBody表示是否有请求体
*/
@HTTP(method = "GET", path = "user/getUserInfo", hasBody = false)
Call<Bean<DataBean2>> getBlog(@Query("uid") String uid);
}
2:封装的工具类
public class RetrofitUtils {
private static volatile RetrofitUtils instance;
private final Retrofit retrofit;
private RetrofitUtils(String baseurl) {
retrofit = new Retrofit.Builder()
.baseUrl(baseurl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static RetrofitUtils getInstance(String baseurl) {
if (instance == null) {
synchronized (RetrofitUtils.class) {
if (instance == null) {
instance = new RetrofitUtils(baseurl);
}
}
}
return instance;
}
public Retrofit getretrofit(){
return retrofit;
}
}
3:使用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = RetrofitUtils.getInstance("https://www.zhaoapi.cn/").getretrofit();
RetrofitService retrofitService = retrofit.create(RetrofitService.class);
Call<Bean<List<DataBean>>> call = retrofitService.getservice();
call.enqueue(new Callback<Bean<List<DataBean>>>() {
@Override
public void onResponse(Call<Bean<List<DataBean>>> call, Response<Bean<List<DataBean>>> response) {
//直接获取到解析后的数据
Bean<List<DataBean>> body = response.body();
List<DataBean> data = body.getData();
for (int i=0;i<data.size();i++){
Log.i("Tag",data.get(i).getName());
}
}
@Override
public void onFailure(Call<Bean<List<DataBean>>> call, Throwable t) {
}
});