okhttp3+retrofit2+rxjava2使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41673194/article/details/80339709

依赖:

    //retrofit2
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
    //rxjava2
    implementation 'io.reactivex.rxjava2:rxjava:2.1.16'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    //okhttp3
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'

权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

RetrofitInterface:

import com.example.rk7.model.bean.JavaBean;

import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * author:Created by WangZhiQiang on 2018/5/16.
 */
public interface RetrofitInterface {
    @GET("nba/?key=71e58b5b2f930eaf1f937407acde08fe&")
    Observable<JavaBean> getCall(@Query("num") int num);

    @POST("product/getCarts")
    @FormUrlEncoded
    Observable<CartBean> getCartBean(@FieldMap HashMap<String, String> map);
}

RetrofitUtil:(Retrofit的简单封装类)

import android.util.Log;

import com.example.rk7.model.callback.RetrofitInterface;

import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * author:Created by WangZhiQiang on 2018/5/16.
 */
public class RetrofitUtil{
    private Retrofit retrofit;
    private static RetrofitUtil retrofitUtil;

    private RetrofitUtil() { }
    private RetrofitUtil(String baseUrl) {
        //第三方的日志拦截器
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //OKhttp3  设置拦截器打印日志
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
//                .addNetworkInterceptor(logInterceptor)
//                .addInterceptor(new LoggingInterceptor())//自定义拦截器
                .readTimeout(50, TimeUnit.SECONDS)
                .writeTimeout(50, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl) //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava2平台
                .client(okHttpClient)//OKhttp3添加到Retrofit
                .build();
    }
    //指定baseUrl
    public static RetrofitUtil getInstance(String baseUrl){
        if (retrofitUtil==null){
            synchronized (RetrofitUtil.class){
                if (null==retrofitUtil){
                    retrofitUtil = new RetrofitUtil(baseUrl);
                }
            }
        }
        return retrofitUtil;
    }
    //默认的baseUrl
    public static RetrofitUtil getInstance(){
        if (null == retrofitUtil){
            return  getInstance("http://api.tianapi.com/");
        }
        return retrofitUtil;
    }
    //获得Retrofit
    public Retrofit getRetrofit(){
        return retrofit;
    }
    //直接获得RetrofitInterface
    public RetrofitInterface getRetrofitInterface(){
        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
        return retrofitInterface;
    }
    //自定义拦截器/上传公共参数
    public static class LoggingInterceptor implements Interceptor {
        @Override public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //请求前--打印请求信息
            long t1 = System.nanoTime();
            Log.e("myMessage",String.format("Sending url %s \n %s \n\n%s \n\n %s",
                    request.url(), chain.connection(), request.headers(),request.body()));

            //网络请求
            okhttp3.Response response = chain.proceed(request);

            //网络响应后--打印响应信息
            long t2 = System.nanoTime();
            Log.e("myMessage",String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));

            return response;

//            上传公共参数
//            Request request = chain.request();
//            Response response = null;
//            Request requestProcess = null ;
//            if("GET".equals(request.method())){
//                String url =  request.url().toString() + "&source=android";
//                Request.Builder builder =  request.newBuilder() ;
//                builder.get().url(url);
//                requestProcess =  builder.build();
//                response = chain.proceed(requestProcess);
//            } else {
//                FormBody.Builder builder = new FormBody.Builder() ;
//                RequestBody requestBody =  request.body() ;
//                if(requestBody instanceof FormBody){
//                    FormBody formBody = (FormBody)requestBody ;
//                    for (int i=0;i<formBody.size();i++){
//                        builder.add(formBody.encodedName(i),formBody.encodedValue(i));
//                    }
//                    builder.add("source","android");
//                }
//                requestProcess =  request.newBuilder().url(request.url().toString()).post(builder.build()).build() ;
//                response = chain.proceed(requestProcess);
//            }
//            return response;
        }
    }
    //日志信息
    public static class HttpLogger implements HttpLoggingInterceptor.Logger {
        @Override
        public void log(String message) {
            Log.e("myMessage", message);
        }
    }
}

使用:

import android.util.Log;

import com.example.rk7.model.bean.JavaBean;
import com.example.rk7.model.http.RetrofitUtil;
import com.example.rk7.view.interfaces.IMainView;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * author:Created by WangZhiQiang on 2018/4/16.
 */
public class MainPresenter extends BasePresenter<IMainView>{
    public void getDataFromServer(int num) {
//        Retrofit retrofit = RetrofitUtil.getInstance().getRetrofit();
//        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
        Observable<JavaBean> observable = RetrofitUtil.getInstance().getRetrofitInterface().getCall(num);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<JavaBean>() {
                    @Override
                    public void accept(JavaBean javaBean) throws Exception {
                        Log.e("getDataFromServer",javaBean.getNewslist().size()+"");
                    }
                });
        //map操作符使用
//        Observable<JavaBean> observable = RetrofitUtil.getInstance().getRetrofitInterface().getCall(num);
//        observable.subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new Function<JavaBean, JavaBean.NewslistBean>() {
//                    @Override
//                    public JavaBean.NewslistBean apply(JavaBean javaBean) throws Exception {
//                        return javaBean.getNewslist().get(0);
//                    }
//                }).subscribe(new Consumer<JavaBean.NewslistBean>() {
//            @Override
//            public void accept(JavaBean.NewslistBean newslistBean) throws Exception {
//                Log.e("getDataFromServer",newslistBean.getTitle()+"");
//            }
//        });
    }
}

JavaBean:

public class JavaBean {
    /**
     * code : 200
     * msg : success
     * newslist : [{"ctime":"2016-12-04 13:00","title":"格林:理解科尔吸食大麻 不过我从没吸过","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161204/1-161204120131.jpg","url":"http://www.51tyw.com/nba/2421.html"},{"ctime":"2016-12-04 00:00","title":"三分纪录延续!火箭队连续19场比赛命中10+三分球","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161203/1-161203233J3.jpg","url":"http://www.51tyw.com/nba/2417.html"},{"ctime":"2016-12-04 00:00","title":"詹姆斯谈三连败:是时候紧起来了 必须打得男人点","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161203/1-161203234010.jpg","url":"http://www.51tyw.com/nba/2418.html"},{"ctime":"2016-12-03 12:00","title":"骑士输赢都靠三分?那还要詹姆斯做什么?","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161203/1-161203104344.jpg","url":"http://www.51tyw.com/nba/2407.html"},{"ctime":"2016-12-03 00:00","title":"公牛vs骑士直播看点:詹伟兄弟对决","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-161202221205.jpg","url":"http://www.51tyw.com/nba/2395.html"},{"ctime":"2016-12-02 22:00","title":"火箭和勇士联手创NBA三分纪录","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-161202214212.jpg","url":"http://www.51tyw.com/nba/2392.html"},{"ctime":"2016-12-02 22:00","title":"巴克利:勇士打得像女式篮球,太软了!","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-161202215032.jpg","url":"http://www.51tyw.com/nba/2394.html"},{"ctime":"2016-12-02 20:00","title":"詹姆斯完成月最佳球员4连霸的壮举!","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-1612021PI0.jpg","url":"http://www.51tyw.com/nba/2388.html"},{"ctime":"2016-12-01 00:00","title":"威少再下三双战书!詹皇会不会先认怂?","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161128/1-16112Q13251.jpg","url":"http://www.51tyw.com/nba/2374.html"},{"ctime":"2016-12-01 00:00","title":"骑士这样的防守想夺冠?也许卫冕只是空谈!","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161130/1-161130222229.jpg","url":"http://www.51tyw.com/nba/2375.html"},{"ctime":"2016-12-01 00:00","title":"2016-2017赛季达拉斯小牛队球员名单","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161130/1-161130223630H8.gif","url":"http://www.51tyw.com/nba/2376.html"},{"ctime":"2016-11-28 12:00","title":"勇士队第一中锋竟是杜兰特","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161128/1-16112Q10H7.jpg","url":"http://www.51tyw.com/nba/2348.html"},{"ctime":"2016-11-28 12:00","title":"三双之战谁怕谁!詹皇三双数据超威少","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161128/1-16112Q12440.jpg","url":"http://www.51tyw.com/nba/2349.html"},{"ctime":"2016-11-28 12:00","title":"队史第一人!杜兰特成首位砍下25+10+5+5的球员","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161128/1-16112Q13251.jpg","url":"http://www.51tyw.com/nba/2350.html"},{"ctime":"2016-11-28 00:00","title":"湖人vs老鹰分析:缺兵少将的湖人恐不敌老鹰","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161127/1-16112H24117.jpg","url":"http://www.51tyw.com/nba/2346.html"},{"ctime":"2016-11-27 22:00","title":"2016-2017赛季亚特兰大老鹰队球员名单","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161125/1-1611251R231A1.gif","url":"http://www.51tyw.com/nba/2344.html"},{"ctime":"2016-11-25 22:00","title":"科比退役赛视频:黑曼巴最后一役砍60分","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161125/1-1611251R231A1.gif","url":"http://www.51tyw.com/nba/2307.html"},{"ctime":"2016-11-25 20:00","title":"NBA官方承认尼克杨绝杀走步","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161125/1-1611251R231A1.gif","url":"http://www.51tyw.com/nba/2304.html"},{"ctime":"2016-11-25 18:00","title":"骑士若无詹皇只能垫底 去76人都能进总决赛","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161125/1-1611251J401.jpg","url":"http://www.51tyw.com/nba/2303.html"},{"ctime":"2016-11-25 02:00","title":"湖人队赛程:2016-2017洛杉矶湖人队赛程表","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161122/1-161122205542.jpg","url":"http://www.51tyw.com/nba/2299.html"}]
     */

    private int code;
    private String msg;
    private List<NewslistBean> newslist;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<NewslistBean> getNewslist() {
        return newslist;
    }

    public void setNewslist(List<NewslistBean> newslist) {
        this.newslist = newslist;
    }

    public static class NewslistBean {
        /**
         * ctime : 2016-12-04 13:00
         * title : 格林:理解科尔吸食大麻 不过我从没吸过
         * description : NBA新闻
         * picUrl : http://www.51tyw.com/uploads/allimg/161204/1-161204120131.jpg
         * url : http://www.51tyw.com/nba/2421.html
         */

        private String ctime;
        private String title;
        private String description;
        private String picUrl;
        private String url;

        public String getCtime() {
            return ctime;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}

 

展开阅读全文

没有更多推荐了,返回首页