Retrofit+OkHttp+RxJava 已经火烧燎原了,如果我还不会的话,实在说不过去了,这几天熬夜在学,平时8点才下班,到家都9点多了了,悲惨的人生啊。
..
准备一个 HttpMan
<pre>
public interface HttpMan {
//钱罐儿 登录
@GET("homePhone/loginPhone/{phone}-{pwd}")
Observable<LoginBean> loginQg(@Path("phone") String phone, @Path("pwd") String pwd);
}
</pre>
准备一个 Presenter
<pre>
/**
* Created by alex on 2016/6/21.
*/
public class QgLoginPresenter {
private IGithubView iGithubView;
public QgLoginPresenter(IGithubView iGithubView) {
this.iGithubView = iGithubView;
}
public void loginFujinguang(String phone, String pwd) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
// Log信息拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
//KLog.e(message);
Logger.t(5).e(message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置 Debug Log 模式
builder.addInterceptor(loggingInterceptor);
}
OkHttpClient okHttpClient = builder.build();
//
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://api.qianguan360.com/service/").client(okHttpClient).addConverterFactory(GsonConverterFactory.create())//添加 json 转换器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加 RxJava 适配器
.build();
HttpMan gitHub = retrofit.create(HttpMan.class);
gitHub.loginQg(phone,pwd).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new MyHttpSubscriber());
}
private final class MyHttpSubscriber extends HttpSubscriber<LoginBean> {
@Override
public void onStart() {
iGithubView.showLoadingLayout();
}
@Override
public void onFailure(int code, String message) {
KLog.e("code = " + code + " message = " + message);
iGithubView.showFailLayout();
iGithubView.onSetFailMessage(message);
}
@Override
public void onSuccess(LoginBean result) {
//KLog.e(result.mobileNo);
Logger.e(result.mobileNo);
iGithubView.showSuccessLayout();
iGithubView.setContextText(result.mobileNo);
}
}
}
</pre>
介绍一下 Retrofit 的注解
..
· 简单 get 直接拼串
<pre>
主域名 http://api.qianguan360.com/service/
接口地址 homePhone/loginPhone/
登录接口 http://api.qianguan360.com/service/homePhone/loginPhone/13146008029-123456
@GET("homePhone/loginPhone/{phone}-{pwd}")
Observable<LoginBean> loginQg(@Path("phone") String phone, @Path("pwd") String pwd);
{} 用花括号包裹的是动态字符串
</pre>
PS:我们需要的 依赖 奉上源码
<pre>
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.orhanobut:logger:1.13'
</pre>