引用的技术
- Retrofit2
- RxJava
- Lombok
目标
使用简单、高效。尽可能让服务和使用者之间不用产生额外的学习成本和使用成本,在尽量不影响使用者源代码结构及编码方式的同时,能大幅提高使用者的开发效率及产品质量。
开始
首先SDK的所有功能都是基于Bmob平台现有的RestfulApi进行实现的,一般来说只要RestfulApi中提供的接口,在SDK中都能找到对应的实现。本篇博客我们先搭建好一个SDK的基本框架,然后简单实现增、删、改三个接口的功能。
接下来我们看一看Bmob数据服务Restful开发文档Restful开发文档,其中注意文档中的两点:
这里说明了所有接口请求时所需的参数与响应的结果是怎样的。图中只给出了错误情况下的固定json格式,其他情况下返回的也是一个JsonObject格式的内容,只是结构内容不是固定的,这里需要看每个接口的说明。
代码讲解
基于Retrofilt2的特性,我们将每个功能接口在BmobApiService接口中进行定义,方法中各注解的使用和含义可以参考Retrofit2的相关文档,这里就不展开讲解了。现在BmobApiService接口中,我们定义了三个方法insert、delete、update分别对应Bmob数据服务RestfulApi中的增、删、改三个接口。
public interface BmobApiService {
@POST("/1/classes/{tableName}")
Call<JsonObject> insert(@Path("tableName")String tableName, @Body Object object);
@DELETE("/1/classes/{tableName}/{objectId}")
Call<JsonObject> delete(@Path("tableName")String tableName, @Path("objectId")String objectId);
@PUT("/1/classes/{tableName}/{objectId}")
Call<JsonObject> update(@Path("tableName")String tableName,
@Path("objectId")String objectId,
@Body Object object);
}
在SDK整个使用过程中常用的数据先用一个BaseConfig类来存放。
public class BaseConfig {
public static String appId = "8b5403b0******ccae9b7057e";
public static String apiKey = "8e97181******31cbce3e630";
/* 基础url */
public static String baseUrl = "https://api.bmob.cn/";
/* 是否调试 */
private boolean debug = false;
}
创建Bmob类使用单例模式提供
public class Bmob {
private volatile static Bmob INSTANCE;
private volatile static BmobApiService mBmobApiService;
private Bmob(){
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(HttpConfig.connectionTime, TimeUnit.SECONDS);
builder.addInterceptor(InterceptorUtil.headerInterceptor()); // 使用拦截器在request中添加统一header内容
if(HttpConfig.debug){
builder.addInterceptor(InterceptorUtil.logInterceptor()); // 添加日志拦截器
}
Retrofit mRetrofit = new Retrofit.Builder()
.client(builder.build())
.baseUrl(HttpConfig.baseUrl)
.addConverterFactory(GsonConverterFactory.create()) // 添加gson转换器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 添加rxjava转换器
.build();
mBmobApiService = mRetrofit.create(BmobApiService.class);
}
public static Bmob getInstance(){
if (null == INSTANCE){
synchronized (Bmob.class){
if (null == INSTANCE){
INSTANCE = new Bmob();
}
}
}
return INSTANCE;
}
public BmobApiService api(){
return mBmobApiService;
}
}
在OkHttpClient中添加的两个拦截器的定义如下:
@Log
public class InterceptorUtil {
/**
* 在Request中添加Header内容
* @return
*/
public static Interceptor headerInterceptor(){
return new Interceptor() {
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/json; charset=UTF-8")
.addHeader("X-Bmob-Application-Id", HttpConfig.appId)
.addHeader("X-Bmob-REST-API-Key", HttpConfig.apiKey)
.build();
return chain.proceed(request);
}
};
}
/**
* 日志拦截器
* @return
*/
public static HttpLoggingInterceptor logInterceptor(){
//日志显示级别
HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;
return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
public void log(String message) {
log.log(Level.INFO, message);
}
}).setLevel(level);
}
}
使用
下面使用Retrofit2的同步方式来请求接口。
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("playerName","张三");
jsonObject.addProperty("score", 59.5);
Call<JsonObject> call = Bmob.getInstance().api().insert("StudentScore", jsonObject);
// 同步请求
try {
Response<JsonObject> ret = call.execute();
// 打印接口返回的数据
System.out.println("result = "+ret.body());
} catch (IOException e) {
e.printStackTrace();
}
其他
代码已提交到GitHub,在原Bmob-Java-SDK项目的v2分支里。
有什么问题或建议可以在项目中提issues啊。
继续
今天基本实现了SDK的框架,这只是开始,接下来会慢慢完善对其他接口的支持,并继续改进和优化SDK的使用方法。
手摸手教你的哦,会了吗?(挑眉、挑眉、挑眉)