1.Retrofit是基于OkHttp网络请求框架的二次封装而已,懂Okhttp的小伙伴,那么Retrofit也就基本都会。
2.Retrofit采用注解配置请求的方式:
3.性能最好,处理最快
4.使用REST API时非常方便;
5.传输层默认就使用OkHttp;
6.支持NIO;
7.拥有出色的API文档和社区支持
8.速度上比volley更快;
9.如果你的应用程序中集成了OKHttp,Retrofit默认会使用OKHttp处理其他网络层请求。
10.默认使用Gson
一:retrofit的使用
Retrofit支持同步和异步两种方式,在使用时,需要将请求地址转换为接口,通过注解来指定请求方法,请求参数,请求头,返回值等信息。get请求到服务器后从数据库查询数据,返回值为查询到的数据,post请求向服务器提交一条数据,返回值为提交的数据。
一:首先完成请求所用的service,是一个interface,完全通过注解完成配置。
倚赖需要的包
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.8.0'
public interface DouBanApiClient {
/**
*@param headers 请求参数头
*@param url 请求的地址
*@param params 请求的参数
*/
@GET()
Call<ResponseBody> get(@HeaderMap Map<String, String> headers, @Url String url, @QueryMap Map<String, String> params);
@FormUrlEncoded
@POST()
Call<String> post(@HeaderMap Map<String, String> headers, @Url String url, @FieldMap Map<String, String> params);
@Streaming
@GET()
Call<ResponseBody> download(@HeaderMap Map<String, String> headers, @Url String url, @QueryMap Map<String, String> params);
}
二:创建一个请求单例 ApiClient,方便管理网络请求,本文只给出get请求的实现方式。
(ApiBuilder 构建的参数 包含 请求 url header params,后文会贴出代码)
/**
*
* 网络请求类
* Created by Administrator on 2017/2/13 0013.
*/
public class ApiClient {
static ApiClient instance;
public final static String BASE_API = "http://app.youxiake.com";
/**
* 请求的接口
* */
public static String Api_BookInfo = "/api/discover/list/hot";
/***
*
* 构建 retrofit请求
* */
private final static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiClient.BASE_API)
.build();
/**
* 获得 DouBanApiClient实例
* @return
*/
public DouBanApiClient getDbService(){
return retrofit.create(DouBanApiClient.class);
}
/**
* 创建请求单例
* @return
*/
public static ApiClient getInstance(){
if(instance == null){
synchronized (ApiClient.class){
if(instance ==null){
instance = new ApiClient();
}
}
}
return instance;
}
/**
*
* get请求
* @param builder request构建的参数 包含 url header params
* @param onCallback rquest 回调
* @param classOf 指定请求的model类型
* @param <T>
*/
public <T> void doGet(ApiBuilder builder ,final com.retrofitdemo.interfaces.CallBack<T> onCallback,final Class classOf){
DouBanApiClient dbService = getDbService();
Call<ResponseBody> stringCall = dbService.get(checkHeaders(builder.headers),
checkUrl(builder.url), checkParams(builder.params));
stringCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Object o = null;
try {
Log.d("TAG","----"+response.body().string());
o = new Gson().fromJson(response.body().string(), classOf);
} catch (IOException e) {
e.printStackTrace();
}
onCallback.onSuccess(call, (T) o);
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
onCallback.onFailure(call,t);
Log.d("TAG","----"+t.getMessage());
}
});
}
private String checkUrl(String url) {
if (checkNULL(url)) {
return null;
}
return url;
}
// 判断是否NULL
public static boolean checkNULL(String str) {
return str == null || "null".equals(str) || "".equals(str);
}
// 判断是否NULL
public static void Error(Context context, String msg) {
if (checkNULL(msg)) {
msg = "未知异常";
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
public static Map<String, String> checkHeaders(Map<String, String> headers) {
if (headers == null) {
headers = new HashMap<>();
}
//retrofit的headers的值不能为null,此处做下校验,防止出错
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (entry.getValue() == null) {
headers.put(entry.getKey(), "");
}
}
return headers;
}
public static Map<String, String> checkParams(Map<String, String> params) {
if (params == null) {
params = new HashMap<>();
}
//retrofit的params的值不能为null,此处做下校验,防止出错
for (Map.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() == null) {
params.put(entry.getKey(), "");
}
}
return params;
}
}
三:构建请求的参数
/**
* Created by cvmars 2017/2/14 0014.
*/
public class ApiBuilder {
Map<String, String> params ;
Map<String, String> headers ;
String url;
public ApiBuilder Params(Map<String, String> params) {
this.params.putAll(params);
return this;
}
public ApiBuilder Params(String key, String value) {
this.params.put(key, value);
return this;
}
public ApiBuilder Headers(Map<String, String> headers) {
this.headers.putAll(headers);
return this;
}
public ApiBuilder Headers(String key, String value) {
this.headers.put(key, value);
return this;
}
public ApiBuilder Url(String url) {
this.url = url;
return this;
}
public ApiBuilder(String url) {
this.setParams(url);
}
public ApiBuilder() {
this.setParams(null);
}
private void setParams(String url) {
this.url = url;
this.params = new HashMap<>();
this.headers = new HashMap<>();
}
}
四:回调接口
public interface CallBack<T> {
void onSuccess(Call<ResponseBody> call, T response);
void onFailure(Call<ResponseBody> call, Throwable t);
}
五:简单的封装基本完成:下面是基本使用方法
先创建返回的model
public class FindContent {
public String msg;
public int code;
public DataBean data;
public static class DataBean {
public int total;
public int totalPage;
public int pageSize;
public List<QuotesListBean> quotesList;
public static class QuotesListBean {
public String content;
public String uid;
public String address;
public String show_address;
public String comment;
public String prise;
public String gmt_create;
public String type;
public String video;
public Object activity;
public String username;
public String avatar;
public int quote_id;
public String relation;
public String share_url;
public boolean prised;
public List<ImagesBean> images;
public List<?> discus;
public static class ImagesBean {
public String width;
public String height;
public String url;
public String url_xl;
public String url_l;
public String url_m;
public List<?> labels_info;
}
}
}
}
在需要请求的地方进行调用
ApiBuilder builder = new ApiBuilder(ApiClient.Api_BookInfo)
.Headers("header1","this is request header")
.Headers("header2","this is request header2")
.Params("params","this is request params");
ApiClient.getInstance().doGet(builder, new CallBack<FindContent>() {
@Override
public void onSuccess(Call<ResponseBody> call, FindContent response) {
mContent.setText(response.toString());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
},FindContent.class);
}
网友评论