gradle 依赖引用:
// glide
implementation 'com.github.bumptech.glide:glide:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.11.0'
//https图片处理
implementation "com.github.bumptech.glide:okhttp3-integration:4.11.0"
别忘了顶部加上
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
先写一个 UnsafeOkHttpClient 类
package com.bdxh.clientstudentandroid.http.glide
import okhttp3.OkHttpClient
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
object UnsafeOkHttpClient {
fun getUnsafeOkHttpClient(): OkHttpClient? {
return try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(
object : X509TrustManager {
override fun checkClientTrusted(
chain: Array<out X509Certificate>?,
authType: String?
) {
}
override fun checkServerTrusted(
chain: Array<out X509Certificate>?,
authType: String?
) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
}
)
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
val builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
builder.hostnameVerifier(HostnameVerifier { _, _ -> true })
builder.connectTimeout(20, TimeUnit.SECONDS)
builder.readTimeout(20, TimeUnit.SECONDS)
builder.build()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
写一个 OkHttpAppGlideModule 类,实现 AppGlideModule 接口,然后加入注解 @GlideModule
package com.bdxh.clientstudentandroid.http.glide
import android.content.Context
import com.bdxh.clientstudentandroid.http.glide.UnsafeOkHttpClient.getUnsafeOkHttpClient
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import java.io.InputStream
@GlideModule
class OkHttpAppGlideModule: AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
val client = getUnsafeOkHttpClient()
client?.let {
registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(client))
}
}
override fun isManifestParsingEnabled(): Boolean {
return false
}
}
用法 :
GlideApp.with(context)
.load(studentHeadImageUrl)
.apply(RequestOptions()
.transform(CenterCrop(), RoundedCorners(20)))
.into(img_upload_head)