【问题标题】:Why is Volley Library usually combined with okHttp Library?为什么 Volley 库通常与 okHttp 库结合使用?
【发布时间】:2015-09-03 19:21:15
【问题描述】:

为什么 Volley 通常会和 okHttp 结合使用?为什么会这样?

例如:

   OkHttpClient client = new OkHttpClient();
   client.networkInterceptors().add(new StethoInterceptor());
   mRequestQueue = Volley.newRequestQueue(context, new OkHttpStack(client));

【问题讨论】:

    标签: android android-volley okhttp


    【解决方案1】:

    Volley 在创建 RequestQueue 时需要一个 HttpStack

    如果您不提供,Volley 将根据您的 API 级别创建一个堆栈:如果您运行的是 API 9 或更低版本,它将基于 AndroidHttpClient。如果您运行的是 API 10 或更高版本,它将基于 HttpURLConnection。

    OkHttp 是一个现代、快速、高效的 Http 客户端,它支持 HTTP/2 和 SPDY,并为您做很多事情,比如连接池、gziping、缓存……等等。 OkHttp 的作用类似于传输层。

    OkHttp 使用 Okio,这是一个补充 java.io 和 java.nio 的库,可以更轻松地访问、存储和处理您的数据。

    出于这些原因,我建议您使用 OkHttp Stack。我正在使用不使用 okhttp-urlconnection 的this one

    我为 Android 网络编写了一个 article about using OkHttp, Volley and Gson,您可能会觉得有趣。

    【讨论】:

    • OkHttp 在内部被 Android 4.4 使用后,我们还需要 HttpStack 吗?
    • @rcde0 KitKat 是几年前发布的,可能有一个非常旧的 OkHttp 版本,这不是您问题的答案,只是需要记住的一点。
    • @ Sotti,我读了你的好文章,但是,android studio 找不到类 - “OkHttpStack”,即使添加后 - 编译'com.google.code.gson:gson:2.7' compile 'com .squareup.okhttp3:okhttp:3.5.0' 编译 'com.android.volley:volley:1.0.0'
    • @CRSardar 在我的回答中(就在上面,您需要提供指向 OkHttpStack 的链接。
    【解决方案2】:

    阅读this 了解为什么 okhttp 适合传输 - 然后您就会知道为什么它经常与 volley 结合使用

    【讨论】:

    • 是因为 volley 无法处理 HTTP 请求?
    • 关注点分离是这里的关键
    • 这并不能真正解释为什么我们需要 Volley
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 2017-06-25
    相关资源
    最近更新 更多