我用的okhttp,所以直接用的同一个client,在网上找的直接用OkhttpDownload不行,看原因是因为2.5.2不支持okhttp3,所以按照他的格式自己写一个
这个项目用的kotlin,直接贴过去就行,java完全兼容
application中设置
//初始化okhttp
val sslParams = HttpsUtils.getSslSocketFactory(null, null, null)
val okHttpClient = OkHttpClient.Builder()
.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS)
.build()
OkHttpUtils.initClient(okHttpClient)
//Picasso 支持https
val picasso = Picasso.Builder(this)
.downloader(MyDownloader(okHttpClient))
.build()
Picasso.setSingletonInstance(picasso)
MyDownloader.kt
package com.cyyz.mobilesignature.utils
import android.net.Uri
import com.squareup.picasso.Downloader
import com.squareup.picasso.NetworkPolicy
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
/**
* Created by TaoYuan on 2017/11/8 0008.
*/
private class MyDownloader(client: OkHttpClient) : Downloader {
private var client: OkHttpClient? = null
init {
this.client = client
}
@Throws(IOException::class)
override fun load(uri: Uri, networkPolicy: Int): Downloader.Response {
var cacheControl: CacheControl? = null
if (networkPolicy != 0) {
if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
cacheControl = CacheControl.FORCE_CACHE
} else {
val builder = CacheControl.Builder()
if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
builder.noCache()
}
if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
builder.noStore()
}
cacheControl = builder.build()
}
}
val builder = Request.Builder().url(uri.toString())
if (cacheControl != null) {
builder.cacheControl(cacheControl)
}
val response = client!!.newCall(builder.build()).execute()
val responseCode = response.code()
if (responseCode >= 300) {
response.body().close()
throw Downloader.ResponseException(responseCode.toString() + " " + response.message(), networkPolicy,
responseCode)
}
val fromCache = response.cacheResponse() != null
val responseBody = response.body()
return Downloader.Response(responseBody.byteStream(), fromCache, responseBody.contentLength())
}
override fun shutdown() {
val cache = client!!.cache()
if (cache != null) {
try {
cache.close()
} catch (ignored: IOException) {
}
}
}
}