发布于 5年前
Kotlin 文件下载类
package com.frowhy.utils
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
/**
* Download
* Created by frowhy on 2017/4/4.
*
* @param fileUrl 文件下载地址
* @param fileName 文件名
* @param filePath 文件保存路径
*/
class Download(fileUrl: String, fileName: String, filePath: String) {
init {
downloadFile(fileUrl, fileName, filePath)
}
private fun downloadFile(fileUrl: String, fileName: String, filePath: String) {
val mFile = File(filePath, fileName)
if (mFile.exists()) {
return
}
// 忽略HTTPS效验
var sslContext: SSLContext? = null
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(
chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<X509Certificate?> {
return arrayOfNulls(0)
}
})
try {
sslContext = SSLContext.getInstance("SSL")
sslContext!!.init(null, trustAllCerts, java.security.SecureRandom())
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
} catch (e: KeyManagementException) {
e.printStackTrace()
}
val mOkHttpClient: OkHttpClient = OkHttpClient.Builder()
// 忽略HTTPS效验
.sslSocketFactory(sslContext!!.socketFactory, object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(
chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<X509Certificate?> {
return arrayOfNulls(0)
}
})
.hostnameVerifier { _, _ -> true }
.build()
val mRequest: Request = Request.Builder()
.url(fileUrl)
.build()
val mResponse: Response = mOkHttpClient.newCall(mRequest)
.execute()
var inStream: InputStream? = null
val buffer = ByteArray(2048)
var length: Int
var outStream: FileOutputStream? = null
try {
val total = mResponse.body().contentLength()
if (total != -1.toLong()) {
var current: Long = 0
inStream = mResponse.body().byteStream()
outStream = FileOutputStream(mFile)
do {
length = inStream.read(buffer)
if (length != -1) {
current += length.toLong()
outStream.write(buffer, 0, length)
}
} while (length != -1)
outStream.flush()
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
if (inStream != null) {
inStream.close()
}
if (outStream != null) {
outStream.close()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}