项目依赖:
compile 'io.reactivex.rxjava2:rxjava:2.0.1' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.okio:okio:1.11.0' compile 'com.jakewharton:butterknife:8.4.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
apply plugin:'com.jakewharton.butterknife'
根依赖:
classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
Retrifit工具类:
package com.example.admin.xiaoshixun_retrofit_rxjava_mvp.RetrofitUtils; import java.util.ArrayList; import java.util.List; import okhttp3.OkHttpClient; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by dell on 2018/1/30. */ public class RetrofitUtils { private static RetrofitUtils retrofitUtils; private static LoginService loginService; //声明私有构造方法,利于单例模式,让调用者无法new出对象,只能通过构造这模式创建对象 public RetrofitUtils(){ } //先后调用的过程,只有builder创建之后,才能调用此方法 public LoginService getTsetService(){ return loginService; } public static class Builder{ ListcallAdapterfactorys=new ArrayList<>(); List converterFactorys=new ArrayList<>(); private OkHttpClient okHttpClient; public Builder addCallAdapterFactory(CallAdapter.Factory factory){ callAdapterfactorys.add(factory); //返回this的作用是可以链式调用 return this; } public Builder addConverterFactory(Converter.Factory factory){ converterFactorys.add(factory); return this; } public Builder client(OkHttpClient okHttpClient){ this.okHttpClient=okHttpClient; return this; } //这个方法才是真正的业务逻辑操作,是真正构建对象的过程 public RetrofitUtils build(){ Retrofit.Builder builder=new Retrofit.Builder(); if(converterFactorys!=null&&converterFactorys.size()==0){ builder.addConverterFactory(GsonConverterFactory.create()); } for (int i = 0; i < converterFactorys.size(); i++) { builder.addConverterFactory(converterFactorys.get(i)); } if(callAdapterfactorys!=null&&callAdapterfactorys.size()==0){ builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create()); } for (int i = 0; i < callAdapterfactorys.size(); i++) { builder.addCallAdapterFactory(callAdapterfactorys.get(i)); } //第一步创建retrofit对象 Retrofit retrofit = builder.client(okHttpClient).baseUrl(Constants.Base_url).build(); //第二步创建Rxjava loginService=retrofit.create(LoginService.class); //第三步请求逻辑(提供给外部访问) retrofitUtils=new RetrofitUtils(); return retrofitUtils; } } }
接口类:
public class Constants { public static String Base_url="https://www.zhaoapi.cn/"; public static String login_url="user/login"; }
请求网络接口的封装接口Service类:
import com.example.admin.xiaoshixun_retrofit_rxjava_mvp.Entity.BaseUser; import com.example.admin.xiaoshixun_retrofit_rxjava_mvp.Entity.User; import java.util.Map; import retrofit2.Call; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import retrofit2.http.Url; /** * Created by dell on 2018/1/30. */ public interface LoginService { @POST @FormUrlEncoded Call> postRetrofit(@Url String url, @FieldMap Map map); }
Entity类:
public class BaseUser<T> { private String msg; private String code; private T data; public void setMsg(String msg) { this.msg = msg; } public void setCode(String code) { this.code = code; } public void setData(T data) { this.data = data; } public String getMsg() { return msg; } public String getCode() { return code; } public T getData() { return data; } }
Entity下User类:
public class User extends BaseUser { private Object age; private String appkey; private String appsecret; private String createtime;
Model:
public interface IModel { //请求网络,为登录做准备 void LoginModel(Mapmap,OnLoginListener onLoginListener); }
public class ModelImpl implements IModel { @Override public void LoginModel(Mapmap, final OnLoginListener onLoginListener) { //创建OkhttpClient OkHttpClient client = new OkHttpClient.Builder().build(); //构造链式调用 new RetrofitUtils .Builder() .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .getTsetService() .postRetrofit(Constants.login_url,map) .enqueue(new Callback >() { //请求成功 @Override public void onResponse(Call > call, Response > response) { Log.e( "onResponse: ",response.body().getMsg() ); onLoginListener.Success(response.body()); } //请求失败 @Override public void onFailure(Call > call, Throwable t) { Log.e( "onFailure: ", t.toString()); onLoginListener.Error(t.toString()); } }); } }
请求网络监听:
public interface OnLoginListener { //成功的方法 void Success(BaseUserbaseUser); //失败的方法 void Error(String error); }
Precenter:
public interface IPrecenter { //联系mv void LoginPrecenter(IModel iModel, IView iView); //mvp解绑 void Destory(); }
public class PrecenterImpl implements IPrecenter { private IView iView; @Override public void LoginPrecenter(IModel iModel, final IView iView) { this.iView = iView; //获取用户名密码做验证 String mobile = iView.getMobile(); String password = iView.getpassword(); if (mobile.length() == 0) { iView.MobileError("手机格式不正确"); } if (password.length() == 0) { iView.PasswordError("密码格式不正确"); } Mapmap = new HashMap<>(); map.put("mobile", mobile); map.put("password", password); iModel.LoginModel(map, new OnLoginListener() { @Override public void Success(BaseUser baseUser) { String code = baseUser.getCode(); if (code.equals("0")) { iView.LoginSuccess(baseUser); } else { iView.failure(baseUser.getMsg()); } } @Override public void Error(String error) { iView.failure(error); } }); } @Override public void Destory() { if (iView != null) { iView = null; } } }
View:
public interface IView { //获取手机号 String getMobile(); //获取密码 String getpassword(); //手机号格式错误 void MobileError(String error); //密码格式错误 void PasswordError(String error); //网络请求成功,登录成功 void LoginSuccess(BaseUserbaseUser); //网络请求失败,登录失败 void LoginError(BaseUser baseUser); //网络请求失败 void failure(String error); }
public class MainActivity extends AppCompatActivity implements IView { @BindView(R.id.ed1) EditText ed1; @BindView(R.id.ed2) EditText ed2; private PrecenterImpl p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //绑定butterknifr ButterKnife.bind(this); p = new PrecenterImpl(); } @OnClick(R.id.login) public void loginButton(View view){ //调中间人 p.LoginPrecenter(new ModelImpl(),this); } @Override public String getMobile() { String trim = ed1.getText().toString().trim(); return trim; } @Override public String getpassword() { String trim = ed2.getText().toString().trim(); return trim; } //手机格式不正确 @Override public void MobileError(String error) { Toast.makeText(this, error, Toast.LENGTH_SHORT).show(); } //密码格式不正确 @Override public void PasswordError(String error) { Toast.makeText(this, error, Toast.LENGTH_SHORT).show(); } //请求网络成功,登录成功 @Override public void LoginSuccess(BaseUserbaseUser) { Toast.makeText(this, baseUser.getData().getUsername()+":"+baseUser.getMsg(), Toast.LENGTH_SHORT).show(); } //请求网络失败,登录失败 @Override public void LoginError(BaseUser baseUser) { Toast.makeText(this, baseUser.getMsg(), Toast.LENGTH_SHORT).show(); } //网络请求失败 @Override public void failure(String error) { Toast.makeText(this, error, Toast.LENGTH_SHORT).show(); } }
xml:
xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.admin.xiaoshixun_retrofit_rxjava_mvp.View.MainActivity">
<EditText
android:id="@+id/ed1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/ed2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="登录"
android:textSize="20px" />
LinearLayout>