注释简化代码的写法public interface LoginService {
@Headers({"Content-Type: application/json","Accept: application/json"})
@POST("login")
Observable<LoginBean> getUserInfo(@Body RequestBody body);
}
登录的请求类(简单封装):public class LoginHttp {
private String host = "http://xxxx/app/user/";
private LoginService loginService;
private Retrofit retrofit;
private LoginHttp(){
retrofit = new Retrofit.Builder()
.baseUrl(host)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
loginService = retrofit.create(LoginService.class);
}
//在访问HttpMethods时创建单例
private static class Holder{
private static final LoginHttp INSTANCE = new LoginHttp();
}
//获取单例
public static final LoginHttp getInstance() {
return LoginHttp.Holder.INSTANCE;
}
public void getUserInFO(Subscriber<LoginBean> subscriber, RequestBody body){
loginService.getUserInfo(body)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
代码调用:subscriber = new Subscriber<LoginBean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e("LoginError",e.getMessage());
Toast.makeText(getApplication(),"登录失败",Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(LoginBean loginBean) {
if (loginBean.getSuccess()){
}
};
LoginHttp.getInstance().getUserInFO(subscriber,body);