简介
Retrofit是基于OkHttp封装的一个网络请求库,Android和Java的类型安全HTTP客户端。Retrofit至少需要Java 8+或Android API 21+,Retrofit的github网址是https://github.com/square/retrofit。
Retrofit基础设置
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://gank.io/api/v2/data/category/Girl/type/Girl/")//设置BaseURL需以'/'结尾
.addConverterFactory(GsonConverterFactory.create())//json解析器Gson
.callbackExecutor(Executors.newSingleThreadExecutor())//使用单独的线程
.build();//创建Retrofit对象
设置BaseUrl和json解析器等一些基础配置
创建请求API
public interface Api {
@GET("page/1/count/10/")
Call> getCall();
数据实体类
public class DemoBean {
private List data;
private int page;
private int page_count;
private int status;
private int total_counts;
public void setData(List data) {
this.data = data;
}
public List getData() {
return data;
}
public void setPage(int page) {
this.page = page;
}
public int getPage() {
return page;
}
public void setPage_count(int page_count) {
this.page_count = page_count;
}
public int getPage_count() {
return page_count;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public void setTotal_counts(int total_counts) {
this.total_counts = total_counts;
}
public int getTotal_counts() {
return total_counts;
}
}
实体类可以根据情况对不需要的字段进行删减。
调用接口方法
public void request(){
Api api = retrofit.create(Api.class);//创建Api代理对象
Call call = api.getCall();//调用接口方法
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
//请求成功回调
Log.d("Retrofit", "onResponse: "+response.body().toString());
}
@Override
public void onFailure(Call call, Throwable t) {
//请求失败回调
}
});
}
接口方法不能直接调用,需要使用Retrofit创建Api代理对象。
总结
本文简单的讲述了一下Retrofit的使用,Retrofit使用的大致流程是:创建Retrofit实例并进行一些基础设置,接着创建请求接口,设置请求方式并声明返回数据类型,最后使用Retrofit创建接口对象,并实现接口方法发送网络请求。