Retrofit+OkHttpClient 封装+Rxjava+MVP

1.首先添加依赖

//butterKnife

compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile 'com.facebook.fresco:fresco:0.11.0'
//retrofit
compile 'io.reactivex.rxjava2:rxjava:2.1.6'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
compile 'com.google.code.gson:gson:2.8.2'
2.添加网络的权限

<uses-permission android:name="android.permission.INTERNET"/>
3.创建包 retrofitUtils

Retrofit+OkHttpClient 封装+Rxjava+MVP_第1张图片

@1.=================================ApiServisce---------------接口=================

public interface ApiService {

    public final static String BASE_URl = "http://112.124.22.238:8081/course_api/";

    /**
     * http://112.124.22.238:8081/course_api/banner/query?type=1
     */
    @GET("banner/query")
    Observable> getData(@Query("type") String type);

    //首页
    @GET("campaign/recommend")
    Observable> getShouData();

    //热卖
    @GET("wares/hot")
    Observable getSellingData(@Query("curPage") int curPage, @Query("pageSize") int pageSize);



    //http://112.124.22.238:8081/course_api/category/list //一级分类
    @GET("category/list")
    Observable> getFenleiData();

    //fenlei 二级 http://112.124.22.238:8081/course_api/wares/list?categoryId=2&curPage=1&pageSize=10
//  categoryId ? int ??Id
//  curPage ? int ????
//  pageSize ? int ????

    @FormUrlEncoded
    @POST("wares/list")
    Observable getTwoFenlei(@FieldMap Map map);

}

@2.===========================RetrofitUtils---类==============
public class RetrofitUtils {

    private RetrofitUtils() {
    }

    private static ApiService apiService;

    public static ApiService getApiService() {
        if (apiService == null) {
            synchronized (RetrofitUtils.class) {
                if (apiService == null) {

                    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            Log.i("aaa", "message====" + message);
                        }
                    });
                    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                    OkHttpClient okHttpClient = new OkHttpClient.Builder()
                            .addInterceptor(new Interceptor() {
                                @Override
                                public okhttp3.Response intercept(Chain chain) throws IOException {
                                    Request request = chain.request();
                                    Log.i("zzz", "request====111111111111111111111111111111");
                                    Log.i("zzz", "request====" + request.headers().toString());
                                    okhttp3.Response proceed = chain.proceed(request);
                                    Log.i("zzz", "proceed====" + proceed.headers().toString());
                                    return proceed;
                                }
                            })
                            .addInterceptor(httpLoggingInterceptor)
                            .build();
                    Retrofit retrofit = new Retrofit.Builder()
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(okHttpClient)
                            .baseUrl(ApiService.BASE_URl)
                            .build();
                    apiService = retrofit.create(ApiService.class);
                }
            }
        }

        return apiService;
    }

}
@3================================= OkHttp3Utils的----类===========
public class OkHttp3Utils {
    /**
     * 懒汉 安全 加同步
     * 私有的静态成员变量 只声明不创建
     * 私有的构造方法
     * 提供返回实例的静态方法
     */
    private static OkHttpClient okHttpClient = null;


    public OkHttp3Utils() {
    }

    public static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            //加同步安全
            synchronized (OkHttp3Utils.class) {
                if (okHttpClient == null) {
                    //判空 为空创建实例
                    // okHttpClient = new OkHttpClient();
/**
 * 和OkHttp2.x有区别的是不能通过OkHttpClient直接设置超时时间和缓存了,而是通过OkHttpClient.Builder来设置,
 * 通过builder配置好OkHttpClient后用builder.build()来返回OkHttpClient,
 * 所以我们通常不会调用new OkHttpClient()来得到OkHttpClient,而是通过builder.build():
 */
                    //  File sdcache = getExternalCacheDir();
                    File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
                    int cacheSize = 10 * 1024 * 1024;
                    okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)).build();
                }
            }

        }

        return okHttpClient;
    }

    /**
     * get请求
     * 参数1 url
     * 参数2 回调Callback
     */

    public static void doGet(String url, Callback callback) {

        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //创建Request
        Request request = new Request.Builder().url(url).build();
        //得到Call对象
        Call call = okHttpClient.newCall(request);
        //执行异步请求
        call.enqueue(callback);


    }

    /**
     * post请求
     * 参数1 url
     * 参数2 回调Callback
     */

    public static void doPost(String url, Map params, Callback callback) {

        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //3.x版本post请求换成FormBody 封装键值对参数

        FormBody.Builder builder = new FormBody.Builder();
        //遍历集合
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));

        }


        //创建Request
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);

    }

    /**
     * post请求上传文件
     * 参数1 url
     * 参数2 回调Callback
     */
    public static void uploadPic(String url, File file, String fileName) {
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //创建RequestBody 封装file参数
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //创建RequestBody 设置类型等
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build();
        //创建Request
        Request request = new Request.Builder().url(url).post(requestBody).build();

        //得到Call
        Call call = okHttpClient.newCall(request);
        //执行请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //上传成功回调 目前不需要处理
            }
        });

    }

    /**
     * Post请求发送JSON数据
     * 参数一:请求Url
     * 参数二:请求的JSON
     * 参数三:请求回调
     */
    public static void doPostJson(String url, String jsonParams, Callback callback) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);


    }

    /**
     * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
     * 参数一:请求Url
     * 参数二:保存文件的路径名
     * 参数三:保存文件的文件名
     */
    public static void download(final MainActivity context, final String url, final String saveDir) {
        Request request = new Request.Builder().url(url).build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("xxx", e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    //apk保存路径
                    final String fileDir = isExistDir(saveDir);
                    //文件
                    File file = new File(fileDir, getNameFromUrl(url));
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show();
                        }
                    });
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }

                    fos.flush();
                    //apk下载完成后 调用系统的安装方法
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    context.startActivity(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();


                }
            }
        });

    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            Log.e("savePath", savePath);
            return savePath;
        }
        return null;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
3.创建bean类的实现 自行创建bean类
4.创建Model层的包 
  

@1.==================IShouModel----接口=======
public interface IShouModel {
    void getData(Observer observer);
}
@2====================ShouModel-----类=======
public class ShouModel implements IShouModel{

    @Override
    public void getData(Observer observer) {
        RetrofitUtils.getApiService().getShouData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
5.创建view的包

@1================== IShouView---接口=======
public interface IShouView {
    void  setShouData(List shouYeBean);
}
6.创建Persenter的包

@1===================== IPersneter-----接口============
public interface IPersneter<V> {
    //mvp 绑定
    void attech(V view);
    //解绑
    void detech();
}
@2====================ShouPersenter--------类==========
public class ShouPresenter implements IPersneter {

    private ShouModel shouModel;
    private SoftReference   softReference;

    public ShouPresenter(IShouView softReference) {
        shouModel=new ShouModel();
        attech(softReference);
    }

    @Override
    public void attech(IShouView view) {
        softReference=new SoftReference(view);
    }

    @Override
    public void detech() {
        softReference.clear();
    }

    public void getDataShou(){
        shouModel.getData(new Observer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }
            @Override
            public void onNext(List shouYeBeans) {
                Log.i("gss","onNext==="+shouYeBeans.size());
                softReference.get().setShouData(shouYeBeans);
            }
            @Override
            public void onError(Throwable e) {
                Log.i("gss","onError==="+e);
            }
            @Override
            public void onComplete() {

            }
        });
    }
}
7.创建BaseAcivity

==============================BaseActivity===========
public abstract class BaseActivity<P extends IPersneter> extends AppCompatActivity {

    P   mPresenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        onCreatePresenter();
    }

    public  abstract  void  onCreatePresenter();
    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除绑定
        mPresenter.detech();
    }

}
8.创建适配器

=================================Myadapter===============
public class Myadapter extends RecyclerView.Adapter {

    private Context context;
    private List listShou;

    public Myadapter(Context context, List listShou) {
        this.context = context;
        this.listShou = listShou;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View   view=View.inflate(context,R.layout.rv_item,null);
       MyViewHolder   holder=new MyViewHolder(view);
       return  holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        holder.tv.setText(listShou.get(position).getTitle());
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(listShou.get(position).getCpOne().getImgUrl())
                .setAutoPlayAnimations(true)
                .build();
        holder.iv.setController(controller);


    }

    @Override
    public int getItemCount() {
        if(listShou==null || listShou.size()<=0)
            return 0;
        return listShou.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private final SimpleDraweeView iv;
        private final TextView tv;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv = (SimpleDraweeView) itemView.findViewById(R.id.img);
            tv = (TextView) itemView.findViewById(R.id.tv);

        }


    }


}
9.终于到了最后的一步在Activity里面的操作
====================================Ativity===================
public class MainActivity extends BaseActivity implements IShouView {

    ShouPresenter shoupp;
    @BindView(R.id.rv)
    RecyclerView rv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(this);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        shoupp=new ShouPresenter(this);
        shoupp.getDataShou();

    }

    @Override
    public void setShouData(List shouYeBean) {

        LinearLayoutManager   manager=new LinearLayoutManager(this);
        rv.setLayoutManager(manager);
        Myadapter    adapter=new Myadapter(this,shouYeBean);
        rv.setAdapter(adapter);
    }

    @Override
    public void onCreatePresenter() {

    }
}








你可能感兴趣的:(Retrofit+OkHttpClient 封装+Rxjava+MVP)