搜索内容

有一个问题?

如果您有任何疑问,可以在下面询问或输入您要寻找的!

Retrofit+RxJava 封装(1)

生成海报
LeeStudio_
LeeStudio_ 2020-09-01 08:41
阅读需:0

此封裝根据Retrofit+Rxjava 最开始版

1.Retrofit互联网封裝:

    private static Retrofit getRetrofit() {
            return new Retrofit.Builder()
                    .baseUrl(Api.Host)
                    .client(NetConfig.getInstance().getClient())
                    .addConverterFactory(GsonConverterFactory.create(NetConfig.getInstance().getGson()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }

baseUrl 是网络服务器主途径

client 互联网封裝

public class NetConfig implements Interceptor, CookieJar {
    private static NetConfig instance;

    private OkHttpClient client;
    private PersistentCookieStore cookieStore;
    private Gson gson;

    private NetConfig() {
    }

    public static NetConfig getInstance() {
        if (instance == null) {
            synchronized (NetConfig.class) {
                instance = new NetConfig();
            }
        }
        return instance;
    }

    public OkHttpClient getClient() {
        if (client == null)
            client = new OkHttpClient.Builder()
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .addInterceptor(this)
                    .cookieJar(this)
                    .build();
        return client;
    }

    public Gson getGson() {
        if (gson == null)
            gson = new GsonBuilder()
                    .registerTypeAdapter(String.class, new StringConverter())
                    .enableComplexMapKeySerialization() //适用Map的key为繁杂目标的方式
                    .create();
        return gson;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Logger.d("URL = " + request.url().toString());
        Request.Builder builder = request.newBuilder();
        builder.addHeader("imei", PhoneInfo.getInstance().getImei())
                .addHeader("model", PhoneInfo.getInstance().getModel())
                .addHeader("brand", PhoneInfo.getInstance().getBrand())
                .addHeader("version", PhoneInfo.getInstance().getVersion())
                .addHeader("channel", PhoneInfo.getInstance().getChannel())
                .addHeader("device", "android");
        Map headers = Utils.getHttpHeaders();
        if (headers != null) {
            for (Map.Entry entry : headers.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Response response = chain.proceed(builder
                .build());
        ResponseBody responseBody = response.body();
        if (null != responseBody) {
            okhttp3.MediaType mediaType = responseBody.contentType();
            if (null != mediaType && "text/html; charset=UTF-8".equals(mediaType.toString())) {
                if (Constant.IS_DEVELOPER && "POST".equals(request.method())) {//复印要求主要参数
                    StringBuilder sb = new StringBuilder();
                    if (request.body() instanceof FormBody) {
                        FormBody body = (FormBody) request.body();
                        if (null != body) {    for (int i = 0; i < body.size(); i++) {
                                sb.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
                            }
                            if (sb.length() > 0) {
                                sb.delete(sb.length() - 1, sb.length());
                                Logger.d("Params ? " + sb.toString());
                            }
                        }
                    }
                }
                String content = responseBody.string();
                Logger.json(content);
                return response.newBuilder()
                        .body(okhttp3.ResponseBody.create(mediaType, content))
                        .build();
            }
        }
        return response;
    }

    @Override
    public void saveFromResponse(HttpUrl url, List cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                getCookieStore().add(url, item);
            }
        }
    }

    @Override
    public List loadForRequest(HttpUrl url) {
        return getCookieStore().get(url);
    }

    private PersistentCookieStore getCookieStore() {
        if (cookieStore == null)
            cookieStore = new PersistentCookieStore(TopAppContext.context);
        return cookieStore;
    }
}

详细的封裝

 class Creator {
        private static ApiService apiService;

        public static ApiService get() {
            if (apiService == null) {
                create();
            }
            return apiService;
        }

        private static synchronized void create() {
            if (apiService == null) {
                apiService = getRetrofit().create(ApiService.class);
            }
        }

        private static Retrofit getRetrofit() {
            return new Retrofit.Builder()
                    .baseUrl(Api.Host)
                    .client(NetConfig.getInstance().getClient())
                    .addConverterFactory(GsonConverterFactory.create(NetConfig.getInstance().getGson()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
    }

RxJava封裝

1.先看来一个 登陆实例
ApiService.Creator.get().login(account, MD5.getMD5(password), Push.getDeviceToken(), Push.getDeviceToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new FlatMapResponse>())
                .flatMap(new FlatMapTopRes())
                .doOnRequest(new Action1() {//进行要求
                    @Override
                    public void call(Long aLong) {
                })
                .doOnTerminate(new Action0() {
                    @Override
                    public void call() {
                    }
                })
                .subscribe(new Subscriber() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(User user) {

                });
new FlatMapResponse<>封裝款式
public class FlatMapResponse implements Func1, Observable> {@Override
    public Observable call(Response response) {
        if (response.isSuccessful()) {
            return Observable.just(response.body());
        } else {
            try {
                return Observable.error(new Error(response.code(), response.errorBody().string()));
            } catch (IOException e) {
                return Observable.error(new Error(response.code(), e.getMessage()));
            }
        }
    }
}

new FlatMapTopRes封裝款式

public class FlatMapTopRes implements Func1, Observable> {
    @Override
    public Observable call(TopResponse response) {
        if (response.getCode() == 200) {
            return Observable.just(response.getData());
        } else {
            return Observable.error(response.getError());
        }
    }
}

第一个flatmap 是Gson分析的bean种类
第二个是回到的bean,能够除掉云计算平台 :如code info 这种公共性回到码和回到信息内容

看了之上封裝却沒有发觉 Observable被观测者
实际上Observable 早已封裝在 Rtrofit中

 @FormUrlEncoded
    @POST("MobileAppv2/login")
    Observable>> login(@Field("account") String account, @Field("password") String password, @Field("push") String deviceToken, @Field("device_id") String deviceId);

<完>

评论
  • 消灭零回复