Created
August 10, 2018 06:44
-
-
Save Hackforid/c663d15e68b9b70953036fb889602bce to your computer and use it in GitHub Desktop.
Fresco HTTP DNS Interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import okhttp3.Interceptor | |
import okhttp3.Response | |
import java.io.IOException | |
/** | |
* Fresco无法直接设置request的header来传递Hostname | |
* 通过提供Interceptor来添加和video相同的httpdns支持 | |
* 同时图片下载的成功与否也会用来对host进行评分 | |
* Created by quan.zhou on 2018/7/11. | |
*/ | |
class FrescoHttpDNSInterceptor : Interceptor { | |
private val mDnsResolver by lazy { KwaiApp.getDnsResolver() } | |
override fun intercept(chain: Interceptor.Chain): Response { | |
val request = chain.request() | |
val uri = request.url().uri() | |
val url = uri.toString() | |
val host = uri.host | |
val IPs = mDnsResolver.resolveHost(host) | |
if (IPs.isNullOrEmpty()) { | |
return chain.proceed(request) | |
} | |
var response: Response? = null | |
var exception: Exception? = null | |
IPs.forEach { ip -> | |
exception = null | |
response = null | |
try { | |
val req = request.newBuilder() | |
.url(url.replace(host, ip.mIP)) | |
.header("Host", host) | |
.build() | |
response = chain.proceed(req) | |
if (response != null && response!!.isSuccessful) { | |
CDNProvider.requestHostSuccess(host) | |
return response!! | |
} | |
} catch (e: Exception) { | |
if (e is IOException) { | |
if (e.message != "Canceled" && NetworkUtils.isNetworkConnected(KwaiApp.getAppContext())) { | |
mDnsResolver.evictIp(ip.mIP) | |
} | |
} | |
exception = e | |
response = null | |
} | |
} | |
if (NetworkUtils.isNetworkConnected(KwaiApp.getAppContext())) { | |
CDNProvider.requestHostFailed(host) | |
} | |
if (response != null) { | |
return response!! | |
} else { | |
throw exception!! | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment