基于LeanCloud Restful API的Retrofit编程

基于LeanCloud Restful API的Retrofit编程

BaaS提供商LeanCloud提供了Restful API,没有提供Retrofit使用教程。

  • 注册用户

注册API设计:

1
2
3
4
5
6
curl -X POST \
-H "X-LC-Id: y0crQpaNCKUq9WFaSMLByoKo-gzGzoHsz" \
-H "X-LC-Key: ihdOweBmtk9yrDbuPEbJfyBb" \
-H "Content-Type: application/json" \
-d '{"username":"hjiang","password":"f32@ds*@&dsa","phone":"18612340000"}' \
https://api.leancloud.cn/1.1/users

登录API设计:

1
2
3
4
5
6
curl -X POST \
-H "Content-Type: application/json" \
-H "X-LC-Id: y0crQpaNCKUq9WFaSMLByoKo-gzGzoHsz" \
-H "X-LC-Key: ihdOweBmtk9yrDbuPEbJfyBb" \
-d '{"username":"hjiang","password":"f32@ds*@&dsa"}' \
https://api.leancloud.cn/1.1/login

Retrofit接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface LeanCloudRetrofitService {

@POST("users")
Call<Object> signUp(@Header("X-LC-Id") String appId,
@Header("X-LC-Key") String appKey,
@Header("Content-Type") String contentType,
@Body RequestBody userinfo);

@POST("login")
Call<Object> signIn(@Header("X-LC-Id") String appId,
@Header("X-LC-Key") String appKey,
@Header("Content-Type") String contentType,
@Body RequestBody userinfo);
}

注册代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
String username = "";
String password = "";
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseurl)
.build();
LeanCloudRetrofitService service = retrofit.create(LeanCloudRetrofitService.class);
String json = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
RequestBody body = RequestBody.create(MediaType.parse(contenttype), json);

Call<Object> call = service.signUp(appid,
appkey,
contenttype,
body);

call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
tvResult.setText(response.body() + "");
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
tvResult.setText(t.getMessage() + "");
}
});

登录代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
String username = "";
String password = "";
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseurl)
.build();
LeanCloudRetrofitService service = retrofit.create(LeanCloudRetrofitService.class);
String json = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
RequestBody body = RequestBody.create(MediaType.parse(contenttype), json);
Call<Object> call = service.signIn(appid,
appkey,
contenttype,
body);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
tvResult.setText(response.body() + "");
}

@Override
public void onFailure(Call<Object> call, Throwable t) {
tvResult.setText(t.getMessage() + "");
}
});
I Don't Want Your Money, I Want Aragaki Yui.