Android网络请求

学习到了一个新名词:链式操作 一种编程模式
1、retrofit
public interface GitHubService {
@GET("users/{user}/repos")
Call> listRepos(@Path("user") String user);
}
public interface PhoneService {
@GET("/apistore/mobilenumber/mobilenumber")
Call 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 call = service.getResult(API_KEY, phoneView.getText().toString());

//3.发送请求
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        //4.处理结果
        if (response.isSuccess()){
            PhoneResult result = response.body();
            if (result != null){
                PhoneResult.RetDataEntity entity = result.getRetData();
            }
        }
    }
    @Override
    public void onFailure(Call call, Throwable t) {
    }
});

2、retrofit+RXJava
//声明接口
@POST("/login")
Observable 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() {
//可以在这里自定义返回数据的类继承于Subscriber,统一处理返回的数据
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Basebean basebean) {
}
});

你可能感兴趣的:(Android网络请求)