【Android架构】基于MVP模式的Retrofit2+RXjava封装之常见问题(四)

简介: 先回顾下之前的【Android架构】基于MVP模式的Retrofit2+RXjava封装(一)【Android架构】基于MVP模式的Retrofit2+RXjava封装之文件下载(二)【Android架构】基于MVP模式的Retrofit2+RXjava封装之文件上传(三)今天要说的是使用Retrofit2和Okhttp 过程中遇到的一些问题。

先回顾下之前的

【Android架构】基于MVP模式的Retrofit2+RXjava封装(一)
【Android架构】基于MVP模式的Retrofit2+RXjava封装之文件下载(二)
【Android架构】基于MVP模式的Retrofit2+RXjava封装之文件上传(三)

今天要说的是使用Retrofit2和Okhttp 过程中遇到的一些问题。

1.上传数组

相信很多人都遇到到这个问题,这里说下笔者的2种方案:

方案一 把整个请求体转换为JSON提交

首先是ApiServer

 @POST("api/goods/send")
    Observable<BaseModel> sendGoods(@Body RequestBody requestBody);

Presenter

   String[] str = new String["123","234"];
   HashMap<String, Object> map = new HashMap<>();
        map.put("province", addressModel.getProvince());
        map.put("city", addressModel.getCity());
        map.put("area", addressModel.getArea());
        map.put("zipcode", addressModel.getZipcode());
        map.put("user_goods_ids", str);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(map));

        mPresenter.sendGoods(requestBody);

方案二 模拟数组

首先是ApiServer

 //商品评论(私有接口)
    @POST("PrivateApi/goods/goodsComment")
    @FormUrlEncoded
    Observable<BaseModel> goodsComment(@FieldMap ArrayMap<String, Object> map);

Presenter

 ArrayMap<String, Object> map = new ArrayMap<>();
            map.put("goods_id", goods_id);
            map.put("content", etElaluate.getText().toString().trim());
            map.put("address", address);
            for (int i = 0; i < data.size(); i++) {
                map.put("img[" + i + "]", data.get(i));
            }
           presenter.goodsComment(map);

2.Cookie 持续化存储

说道这里,不得不说,Okhttp还是强大

 client = new OkHttpClient.Builder()
                .cookieJar(new CookiesManager(MyApplication.getContext()))
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
//                .sslSocketFactory()
                .build();

创建OkHttpClient时,可以传递一个实现了CookieJar 的自定义管理cookie类,只需要重写其saveFromResponse(HttpUrl url, List<Cookie> cookies)和loadForRequest(HttpUrl url)方法。
这2个方法的作用也很明显,一个是保存cookie,一个是获取cookie

public class CookiesManager implements CookieJar {

    private final PersistentCookieStore cookieStore;

    public CookiesManager(Context context) {
        cookieStore = new PersistentCookieStore(context);
    }



    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
            }
        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url);
        return cookies;
    }
}

PersistentCookieStore

public class PersistentCookieStore {

    private static final String LOG_TAG = "PersistentCookieStore";
    public static final String COOKIE_PREFS = "Cookies_Prefs";
    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
    private final SharedPreferences cookiePrefs;

    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new ArrayMap<>();

        //将持久化的cookies缓存到内存中 即map cookies
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey())) {
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                        }
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }
        }
    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }

  public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        //将cookies缓存到内存中 如果缓存过期 就重置此cookie
        if (!cookie.persistent()) {
            if (!cookies.containsKey(url.host())) {
                cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
            }
            cookies.get(url.host()).put(name, cookie);
        } else {
            if (cookies.containsKey(url.host())) {
                if (cookies.get(url.host()) != null) {
                    cookies.get(url.host()).remove(name);
                }
            }
        }

        if (cookies.get(url.host()) != null) {

            //讲cookies持久化到本地
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
            prefsWriter.apply();
        }
    }
    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());
        return ret;
    }

    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        cookies.clear();
        return true;
    }

    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
            cookies.get(url.host()).remove(name);

            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(name)) {
                prefsWriter.remove(name);
            }
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.apply();

            return true;
        } else {
            return false;
        }
    }

    public List<Cookie> getCookies() {
        ArrayList<Cookie> ret = new ArrayList<>();
        for (String key : cookies.keySet())
            ret.addAll(cookies.get(key).values());

        return ret;
    }

    /**
     * cookies 序列化成 string
     *
     * @param cookie 要序列化的cookie
     * @return 序列化之后的string
     */
    protected String encodeCookie(SerializableOkHttpCookies cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in encodeCookie", e);
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * 将字符串反序列化成cookies
     *
     * @param cookieString cookies string
     * @return cookie object
     */
    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in decodeCookie", e);
        } catch (ClassNotFoundException e) {
            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
        }

        return cookie;
    }

    /**
     * 二进制数组转十六进制字符串
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * 十六进制字符串转二进制数组
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}

SerializableOkHttpCookies

public class SerializableOkHttpCookies implements Serializable {

    private transient final Cookie cookies;
    private transient Cookie clientCookies;

    public SerializableOkHttpCookies(Cookie cookies) {
        this.cookies = cookies;
    }

    public Cookie getCookies() {
        Cookie bestCookies = cookies;
        if (clientCookies != null) {
            bestCookies = clientCookies;
        }
        return bestCookies;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(cookies.name());
        out.writeObject(cookies.value());
        out.writeLong(cookies.expiresAt());
        out.writeObject(cookies.domain());
        out.writeObject(cookies.path());
        out.writeBoolean(cookies.secure());
        out.writeBoolean(cookies.httpOnly());
        out.writeBoolean(cookies.hostOnly());
        out.writeBoolean(cookies.persistent());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        String name = (String) in.readObject();
        String value = (String) in.readObject();
        long expiresAt = in.readLong();
        String domain = (String) in.readObject();
        String path = (String) in.readObject();
        boolean secure = in.readBoolean();
        boolean httpOnly = in.readBoolean();
        boolean hostOnly = in.readBoolean();
        boolean persistent = in.readBoolean();
        Cookie.Builder builder = new Cookie.Builder();
        builder = builder.name(name);
        builder = builder.value(value);
        builder = builder.expiresAt(expiresAt);
        builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
        builder = builder.path(path);
        builder = secure ? builder.secure() : builder;
        builder = httpOnly ? builder.httpOnly() : builder;
        clientCookies =builder.build();
    }
}

此方法可供参考,也可以用其他方式实现,比如说ACache。

3.添加统一请求头

跟cookie一样,okhttp中已经实现
在创建OkHttpClient时,可以添加自定义的拦截器

   client = new OkHttpClient.Builder()
                //添加log拦截器
                .addInterceptor(headInterceptor)
                .addInterceptor(interceptor)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
//                .sslSocketFactory()
                .build();
 private Interceptor headInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();
             Request.Builder builder = request.newBuilder().addHeader("LEDAYOUXUAN", "159357456")
                    .addHeader("APP_TOKEN", UserImpl.getAppToken());

            return chain.proceed(builder.build());
        }
    };

还有一种特别坑的情况,统一请求参数需要添加到请求body中

处理方式还是在拦截器中,不过要区分get和post,注意post无参的情况

 private Interceptor headInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();

            //获取到方法
            String method = request.method();
            if (method.equals("GET")) {
                HttpUrl httpUrlurl = request.url();
                String url = httpUrlurl.toString();
                int index = url.indexOf("?");
                if (index > 0) {
                    url = url + "&APP_KEY=" + AppConstant.APP_KEY;
                } else {
                    url = url + "?APP_KEY=" + AppConstant.APP_KEY;  //拼接新的url
                }
                request = request.newBuilder().url(url).build();  //重新构建请求

            } else if (method.equals("POST")) {
                Request.Builder requestBuilder = request.newBuilder();

                //请求体定制:统一添加token参数
                if (request.body().contentLength() == 0) {
                    //没有参数
                    FormBody.Builder newFormBody = new FormBody.Builder();
                    newFormBody.add("APP_KEY", AppConstant.APP_KEY);
                    newFormBody.add("APP_TOKEN", UserImpl.getAppToken());
                    newFormBody.add("version", AppUtils.getVersionName(MyApplication.getInstance()));
                    requestBuilder.method(request.method(), newFormBody.build());
                } else if (request.body() instanceof FormBody) {
                    //正常post
                    FormBody.Builder newFormBody = new FormBody.Builder();
                    FormBody oidFormBody = (FormBody) request.body();
                    for (int i = 0; i < oidFormBody.size(); i++) {
                        newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i));
                    }
                    newFormBody.add("APP_KEY", AppConstant.APP_KEY);
                    newFormBody.add("APP_TOKEN", UserImpl.getAppToken());
                    newFormBody.add("version", AppUtils.getVersionName(MyApplication.getInstance()));
                    requestBuilder.method(request.method(), newFormBody.build());

                }

                request = requestBuilder.build();

            }

            return chain.proceed(request);
        }
    };

PS:当请求使用 @Multipart注解时,这里还有点问题,目前我的处理方式是在这些方法中手动添加需要的公共参数,有已经实现的小伙伴可以告诉我。

这里会引申出一个问题,原生与h5混合开发时,h5也需要cookie的处理,这会在下篇博客中涉及到。

4.POST无参数

正常post 需要添加@FormUrlEncoded 注解,当post 无参时,只需要去掉该注解即可。

@POST("PrivateApi/Users/verifySecond")
Observable<BaseModel> verifySecond();
目录
相关文章
|
15天前
|
开发工具 Android开发
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
194 11
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
|
5月前
|
缓存 JavaScript 前端开发
Android WebView常见问题
本文主要介绍了在Android开发中WebView的使用方法,包括加载网址、设置相关属性(如JavaScript支持、缓存模式、屏幕适配等)、监听网页加载过程以及返回上一页面的功能实现。同时针对Android P版本限制明文流量的问题(ERR_CLEARTEXT_NOT_PERMITTED),提供了在`AndroidManifest.xml`中添加`android:usesCleartextTraffic=&quot;true&quot;`的解决办法。文章还附有完整代码示例,帮助开发者快速上手并解决常见问题。希望对您的开发工作有所帮助!
267 1
|
6月前
|
数据采集 运维 Serverless
云函数采集架构:Serverless模式下的动态IP与冷启动优化
本文探讨了在Serverless架构中使用云函数进行网页数据采集的挑战与解决方案。针对动态IP、冷启动及目标网站反爬策略等问题,提出了动态代理IP、请求头优化、云函数预热及容错设计等方法。通过网易云音乐歌曲信息采集案例,展示了如何结合Python代码实现高效的数据抓取,包括搜索、歌词与评论的获取。此方案不仅解决了传统采集方式在Serverless环境下的局限,还提升了系统的稳定性和性能。
163 0
|
10月前
|
NoSQL 关系型数据库 MySQL
《docker高级篇(大厂进阶):4.Docker网络》包括:是什么、常用基本命令、能干嘛、网络模式、docker平台架构图解
《docker高级篇(大厂进阶):4.Docker网络》包括:是什么、常用基本命令、能干嘛、网络模式、docker平台架构图解
343 56
《docker高级篇(大厂进阶):4.Docker网络》包括:是什么、常用基本命令、能干嘛、网络模式、docker平台架构图解
|
7月前
|
运维 供应链 前端开发
中小医院云HIS系统源码,系统融合HIS与EMR功能,采用B/S架构与SaaS模式,快速交付并简化运维
这是一套专为中小医院和乡镇卫生院设计的云HIS系统源码,基于云端部署,采用B/S架构与SaaS模式,快速交付并简化运维。系统融合HIS与EMR功能,涵盖门诊挂号、预约管理、一体化电子病历、医生护士工作站、收费财务、药品进销存及统计分析等模块。技术栈包括前端Angular+Nginx,后端Java+Spring系列框架,数据库使用MySQL+MyCat。该系统实现患者管理、医嘱处理、费用结算、药品管控等核心业务全流程数字化,助力医疗机构提升效率和服务质量。
366 4
|
8月前
|
Android开发 开发者 Kotlin
Android实战经验之Kotlin中快速实现MVI架构
MVI架构通过单向数据流和不可变状态,提供了一种清晰、可预测的状态管理方式。在Kotlin中实现MVI架构,不仅提高了代码的可维护性和可测试性,还能更好地应对复杂的UI交互和状态管理。通过本文的介绍,希望开发者能够掌握MVI架构的核心思想,并在实际项目中灵活应用。
344 8
|
10月前
|
网络协议 Linux Android开发
深入探索Android系统架构与性能优化
本文旨在为读者提供一个全面的视角,以理解Android系统的架构及其关键组件。我们将探讨Android的发展历程、核心特性以及如何通过有效的策略来提升应用的性能和用户体验。本文不包含常规的技术细节,而是聚焦于系统架构层面的深入分析,以及针对开发者的实际优化建议。
283 21
|
10月前
|
开发工具 Android开发 iOS开发
Android与iOS生态差异深度剖析:技术架构、开发体验与市场影响####
本文旨在深入探讨Android与iOS两大移动操作系统在技术架构、开发环境及市场表现上的核心差异,为开发者和技术爱好者提供全面的视角。通过对比分析,揭示两者如何塑造了当今多样化的移动应用生态,并对未来发展趋势进行了展望。 ####
|
Android开发 流计算
【Android架构】基于MVP模式的Retrofit2+RXjava封装之文件下载(二)
上篇中我们介绍了基于MVP的Retrofit2+RXjava封装,还没有看的点击这里,这一篇我们来说说文件下载的实现。 首先,我们先在ApiServer定义好调用的接口 @GET Observable downloadFile(@Url St...
1422 0

热门文章

最新文章