学习到了一个新名词:链式操作 一种编程模式
1、retrofit
public interface GitHubService {
@GET("users/{user}/repos")
Call<list<repo>> listRepos(@Path("user") String user);
}
public interface PhoneService {
@GET("/apistore/mobilenumber/mobilenumber")
Call<phoneresult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);
}
使用:
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())//解析方法
.baseUrl(BASE_URL)//主机地址
.build();
//2.创建访问API的请求
PhoneService service = retrofit.create(PhoneService.class);
Call<phoneresult> call = service.getResult(API_KEY, phoneView.getText().toString());
//3.发送请求
call.enqueue(new Callback<phoneresult>() {
@Override
public void onResponse(Call<phoneresult> call, Response<phoneresult> response) {
//4.处理结果
if (response.isSuccess()){
PhoneResult result = response.body();
if (result != null){
PhoneResult.RetDataEntity entity = result.getRetData();
}
}
}
@Override
public void onFailure(Call<phoneresult> call, Throwable t) {
}
});
2、retrofit+RXJava
//声明接口
@POST("/login")
Observable<Basebean> login();
//实现请求
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
retrofit.create(UserService.class).login()
.subscribeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Basebean>() {
//可以在这里自定义返回数据的类继承于Subscriber,统一处理返回的数据
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Basebean basebean) {
}
});