Okhttp+Retrofit+Rxjava+MVP联合使用

来源:互联网 发布:sql表字段设置默认值 编辑:程序博客网 时间:2024/05/16 01:57

在这里我只是简单的实现了他们的简单联合的使用,改进的东西还有很多

请看代码,类比较多


1:添加依赖

 compile 'com.android.support:appcompat-v7:26.+'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    testCompile 'junit:junit:4.12'    compile 'com.squareup.retrofit2:retrofit:2.0.2'// Retrofit库    compile 'com.squareup.okhttp3:okhttp:3.1.2'// Okhttp库    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'//gson解析器    compile 'io.reactivex:rxjava:1.0.14'    compile 'io.reactivex:rxandroid:1.0.1'    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

2:拦截器

import android.util.Log;import java.io.IOException;import okhttp3.FormBody;import okhttp3.Interceptor;import okhttp3.MediaType;import okhttp3.Request;import okhttp3.Response;import okhttp3.ResponseBody;public class LogInterceptor implements Interceptor {    public static String TAG = "LogInterceptor";    @Override    public Response intercept(Interceptor.Chain chain) throws IOException {        Request request = chain.request();        long startTime = System.currentTimeMillis();        Response response = chain.proceed(chain.request());        long endTime = System.currentTimeMillis();        long duration=endTime-startTime;        MediaType mediaType = response.body().contentType();        String content = response.body().string();        Log.d(TAG,"\n");        Log.d(TAG,"----------Start----------------");        Log.d(TAG, "| "+request.toString());        String method=request.method();        if("POST".equals(method)){            StringBuilder sb = new StringBuilder();            if (request.body() instanceof FormBody) {                FormBody body = (FormBody) request.body();                for (int i = 0; i < body.size(); i++) {                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");                }                sb.delete(sb.length() - 1, sb.length());                Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");            }        }        Log.d(TAG, "| Response:" + content);        Log.d(TAG,"----------End:"+duration+"毫秒----------");        return response.newBuilder()                .body(ResponseBody.create(mediaType, content))                .build();    }}

3:Retrofit简单封装

import java.util.concurrent.TimeUnit;import okhttp3.OkHttpClient;import retrofit2.GsonConverterFactory;import retrofit2.Retrofit;import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;/** * Created by dell on 2017/11/20. */public class RetrofitUtils {    public static RetrofitInterface doHttpDeal(String url) {        OkHttpClient client = new OkHttpClient.Builder()                .connectTimeout(5, TimeUnit.SECONDS)                .readTimeout(5, TimeUnit.SECONDS)                .addInterceptor(new LogInterceptor())//              .addNetworkInterceptor(new MyInterceptro())                .build();        Retrofit retrofit = new Retrofit.Builder()                .addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .client(client)                .baseUrl(url)                .build();        RetrofitInterface api = retrofit.create(RetrofitInterface.class);        return api;    }}

4:Retrofit接口

public interface RetrofitInterface {    public static final String BASE_URL = "https://www.zhaoapi.cn/";    // https://www.zhaoapi.cn/?mobile=13691032315&password=123456    @POST("user/login")    Observable<UserBean> getstring(@Query("mobile") String mobile,                                   @Query("password") String password);}

5:view层

public interface MainView {    void success(UserBean msg);    void error(Call call);}

6:model层

import retrofit2.Call;import rx.Subscriber;import rx.android.schedulers.AndroidSchedulers;import rx.schedulers.Schedulers;/** * Created by dell on 2017/11/20. */public class MainModel {    private IMainModel iMainModel;    public void setiMainModel(IMainModel iMainModel) {        this.iMainModel = iMainModel;    }    public void getData(){        RetrofitInterface requestServes = RetrofitUtils.doHttpDeal(RetrofitInterface.BASE_URL);        requestServes.getstring("13691032315","123456").subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe(new Subscriber<UserBean>() {                    @Override                    public void onCompleted() {                    }                    @Override                    public void onError(Throwable e) {                      //  iMainModel.geterror(e);                    }                    @Override                    public void onNext(UserBean userBean) {                     iMainModel.getsuccess(userBean);                    }                });    }    public interface IMainModel{        void getsuccess(UserBean msg);        void geterror(Call call);    }}
7:present层

public class MainPresenter implements MainModel.IMainModel{    private MainModel model;    private MainView view;    public MainPresenter(MainView view) {        this.view = view;        model=new MainModel();        model.setiMainModel(this);    }    public void adddata(){        model.getData();    }    @Override    public void getsuccess(UserBean msg) {        view.success(msg);    }    @Override        public void geterror(Call call) {        view.error(call);    }}

8:Activity.class

public class MainActivity extends AppCompatActivity implements MainView{    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        MainPresenter presenter=new MainPresenter(this);        presenter.adddata();    }    @Override    public void success(UserBean msg) {        Log.d("chenggong",msg.toString());    }    @Override    public void error(Call call) {        Toast.makeText(MainActivity.this,call.toString().toString(),Toast.LENGTH_SHORT).show();        Log.d("shibai",call.toString());    }}




原创粉丝点击