日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

Android端HTTPDNS+Webview最佳實(shí)踐

重要

  • 本文檔為Android WebView場景下接入HTTPDNS的參考方案,提供的相關(guān)代碼也為參考代碼,非線上生產(chǎn)環(huán)境正式代碼,建議您仔細(xì)閱讀本文檔,進(jìn)行合理評估后再進(jìn)行接入。

  • 由于Android生態(tài)碎片化嚴(yán)重,各廠商也進(jìn)行了不同程度的定制,建議您灰度接入,并監(jiān)控線上異常,有問題歡迎您隨時通過技術(shù)支持向我們反饋,方便我們及時優(yōu)化。

  • 當(dāng)前最佳實(shí)踐文檔只針對結(jié)合使用時,如何使用HTTPDNS解析出的IP,關(guān)于HTTPDNS本身的解析服務(wù),請先查看Android SDK接入

背景說明

阿里云HTTPDNS是避免DNS劫持的一種有效手段,在許多特殊場景如Android端HTTPS(含SNI)業(yè)務(wù)場景:IP直連方案Android端HTTPDNS+OkHttp接入指南等都有最佳實(shí)踐,但在webview場景下卻一直沒完美的解決方案。

但這并不代表在WebView場景下我們完全無法使用HTTPDNS,事實(shí)上很多場景依然可以通過HTTPDNS進(jìn)行IP直連,本文旨在給出AndroidHTTPDNS+WebView最佳實(shí)踐供用戶參考。

代碼示例

HTTPDNS+WebView最佳實(shí)踐完整代碼請參考WebView+HTTPDNS Android Demo

攔截接口說明

void setWebViewClient (WebViewClient client);

WebView提供了setWebViewClient接口對網(wǎng)絡(luò)請求進(jìn)行攔截,通過重載WebViewClient中的shouldInterceptRequest方法,我們可以攔截到所有的網(wǎng)絡(luò)請求:

public class WebViewClient {
    // API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        ...
    }

   // API >= 21
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        ...
    }
  ......

}

shouldInterceptRequest有兩個版本:

  • 當(dāng)API < 21時,shouldInterceptRequest方法的版本為:

    public WebResourceResponse shouldInterceptRequest(WebView view, String url)

    此時僅能獲取到請求URL,請求方法、頭部信息以及body等均無法獲取,強(qiáng)行攔截該請求可能無法能到正確響應(yīng)。所以當(dāng)API < 21時,不對請求進(jìn)行攔截:

    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
      return super.shouldInterceptRequest(view, url);
    }
  • 當(dāng)API >= 21時,shouldInterceptRequest提供了新版:

    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)

    其中WebResourceRequest結(jié)構(gòu)為:

    public interface WebResourceRequest {
        Uri getUrl(); // 請求URL
        boolean isForMainFrame(); // 是否由主MainFrame發(fā)出的請求
        boolean isRedirect();  //是否重定向請求
        boolean hasGesture(); // 是否是由某種行為(如點(diǎn)擊)觸發(fā)
        String getMethod(); // 請求方法
        Map<String, String> getRequestHeaders(); // 頭部信息
    }

可以看到,在API >= 21時,在攔截請求時,可以獲取到如下信息:

  • 請求URL

  • 請求方法:POST, GET…

  • 請求頭

實(shí)踐使用

WebView場景下的請求攔截邏輯如下所示:

WebView場景下的請求攔截邏輯

  1. 僅攔截GET請求

  2. 設(shè)置頭部信息

  3. HTTPS請求證書校驗(yàn)

  4. SNI場景

  5. 重定向

  6. MIME&Encoding

僅攔截GET請求

由于WebResourceRequest并沒有提供請求body信息,所以只能攔截GET請求,代碼示例如下:

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    val scheme = request!!.url.scheme!!.trim()
    val method = request.method
    val headerFields = request.requestHeaders
    val url = request.url.toString()
    // 無法攔截body,攔截方案只能正常處理不帶body的請求;
    if ((scheme.equals("http", ignoreCase = true) || scheme.equals("https", ignoreCase = true))
        && method.equals("get", ignoreCase = true)
    ) {
        //TODO 在 設(shè)置頭部信息 部分介紹
    } else {
        return super.shouldInterceptRequest(view, request)
    }
}
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    String scheme = request.getUrl().getScheme().trim();
    String method = request.getMethod();
    Map<String, String> headerFields = request.getRequestHeaders();
    String url = request.getUrl().toString();
    // 無法攔截body,攔截方案只能正常處理不帶body的請求;
    if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
            && method.equalsIgnoreCase("get")) {
        //TODO 在 設(shè)置頭部信息 部分介紹
    } else {
        return super.shouldInterceptRequest(view, request);
    }
}

設(shè)置頭部信息

這里把請求資源的方法抽象出來。

fun recursiveRequest(
    path: String,
    headers: Map<String?, String?>?,
    reffer: String?
): URLConnection? {
    val conn: HttpURLConnection
    var url: URL? = null
    try {
        url = URL(path)
        // 同步接口獲取IP
        val httpdnsResult = HttpDns.getService(context, accountID)
            .getHttpDnsResultForHostSync(url.host, RequestIpType.both)
        var ip: String? = null
        if (httpdnsResult.ips != null && httpdnsResult.ips.isNotEmpty()) {
            ip = httpdnsResult.ips[0]
        } else if (httpdnsResult.ipv6s != null && httpdnsResult.ipv6s.isNotEmpty()) {
            ip = httpdnsResult.ipv6s[0]
        }
        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            val newUrl = path.replaceFirst(url.host.toRegex(), ip!!)
            conn = URL(newUrl).openConnection() as HttpURLConnection
            conn.connectTimeout = 30000
            conn.readTimeout = 30000
            conn.instanceFollowRedirects = false
            // 添加原有頭部信息
            if (headers != null) {
                headers.forEach{ entry ->
                    conn.setRequestProperty(entry.key, entry.value)
                }
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.host)

            //TODO 在 HTTPS請求證書校驗(yàn) 部分介紹
        } else {
            return null
        }

        //TODO 在 重定向 部分介紹
    } catch (e: MalformedURLException) {
        Log.w(TAG, "recursiveRequest MalformedURLException")
    } catch (e: IOException) {
        Log.w(TAG, "recursiveRequest IOException")
    } catch (e: Exception) {
        Log.w(TAG, "unknow exception")
    }
    return null
}
public URLConnection recursiveRequest(String path, Map<String, String> headers, String reffer) {
    HttpURLConnection conn;
    URL url = null;
    try {
        url = new URL(path);
        // 同步接口獲取IP
        HTTPDNSResult httpdnsResult = HttpDns.getService(context, accountID).getHttpDnsResultForHostSync(url.getHost(), RequestIpType.both);

        String ip = null;
        if (httpdnsResult.getIps() != null && httpdnsResult.getIps().length > 0) {
            ip = httpdnsResult.getIps()[0];
        } else if (httpdnsResult.getIpv6s() != null && httpdnsResult.getIpv6s().length > 0) {
            ip = httpdnsResult.getIpv6s()[0];
        }

        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            String newUrl = path.replaceFirst(url.getHost(), ip);
            conn = (HttpURLConnection) new URL(newUrl).openConnection();

            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            // 添加原有頭部信息
            if (headers != null) {
                for (Map.Entry<String, String> field : headers.entrySet()) {
                    conn.setRequestProperty(field.getKey(), field.getValue());
                }
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.getHost());

            //TODO 在 HTTPS請求證書校驗(yàn) 部分介紹
        } else {
            return null;
        }        
        
        //TODO 在 重定向 部分介紹
    } catch (MalformedURLException e) {
        Log.w(TAG, "recursiveRequest MalformedURLException");
    } catch (IOException e) {
        Log.w(TAG, "recursiveRequest IOException");
    } catch (Exception e) {
        Log.w(TAG, "unknow exception");
    }
    return null;
}
override fun shouldInterceptRequest(
    view: WebView?,
    request: WebResourceRequest?
): WebResourceResponse? {
    val scheme = request!!.url.scheme!!.trim()
    val method = request.method
    val headerFields = request.requestHeaders
    val url = request.url.toString()
    // 無法攔截body,攔截方案只能正常處理不帶body的請求;
    if ((scheme.equals("http", ignoreCase = true) || scheme.equals("https", ignoreCase = true))
        && method.equals("get", ignoreCase = true)
    ) {
        try {
            val connection = recursiveRequest(url, headerFields, null)
                ?: return super.shouldInterceptRequest(view, request)

            //TODO 在 MIME&Encoding 部分介紹
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    return super.shouldInterceptRequest(view, request)
}
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    String scheme = request.getUrl().getScheme().trim();
    String method = request.getMethod();
    Map<String, String> headerFields = request.getRequestHeaders();
    String url = request.getUrl().toString();
    // 無法攔截body,攔截方案只能正常處理不帶body的請求;
    if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
            && method.equalsIgnoreCase("get")) {
        try {
            URLConnection connection = recursiveRequest(url, headerFields, null);

            if (connection == null) {
                return super.shouldInterceptRequest(view, request);
            }

            //TODO 在 MIME&Encoding 部分介紹
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 
    return super.shouldInterceptRequest(view, request);
}

HTTPS請求證書校驗(yàn)

如果攔截到的請求是HTTPS請求,需要進(jìn)行證書校驗(yàn):

fun recursiveRequest(
    path: String,
    headers: Map<String?, String?>?,
    reffer: String?
): URLConnection? {
    val conn: HttpURLConnection
    var url: URL? = null
    try {
        url = URL(path)
        // 同步接口獲取IP
        val httpdnsResult = HttpDns.getService(context, accountID)
            .getHttpDnsResultForHostSync(url.host, RequestIpType.both)
        var ip: String? = null
        if (httpdnsResult.ips != null && httpdnsResult.ips.size > 0) {
            ip = httpdnsResult.ips[0]
        } else if (httpdnsResult.ipv6s != null && httpdnsResult.ipv6s.size > 0) {
            ip = httpdnsResult.ipv6s[0]
        }
        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            val newUrl = path.replaceFirst(url.host.toRegex(), ip!!)
            conn = URL(newUrl).openConnection() as HttpURLConnection
            conn.connectTimeout = 30000
            conn.readTimeout = 30000
            conn.instanceFollowRedirects = false
            // 添加原有頭部信息
            headers?.forEach{ entry ->
                conn.setRequestProperty(entry.key, entry.value)
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.host)
            if (conn is HttpsURLConnection) {
                // https場景,證書校驗(yàn)
                conn.hostnameVerifier =
                    HostnameVerifier { _, session ->
                        var host = conn.getRequestProperty("Host")
                        if (null == host) {
                            host = conn.url.host
                        }
                        HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session)
                    }

                //TODO 在 SNI場景 部分介紹
            }

            //TODO 在 重定向 部分介紹
        } else {
            return null
        }
    } catch (e: MalformedURLException) {
        Log.w(TAG, "recursiveRequest MalformedURLException")
    } catch (e: IOException) {
        Log.w(TAG, "recursiveRequest IOException")
    } catch (e: Exception) {
        Log.w(TAG, "unknow exception")
    }
    return null
}
public URLConnection recursiveRequest(String path, Map<String, String> headers, String reffer) {
    HttpURLConnection conn;
    URL url = null;
    try {
        url = new URL(path);
        // 同步接口獲取IP
        HTTPDNSResult httpdnsResult = HttpDns.getService(context, accountID).getHttpDnsResultForHostSync(url.getHost(), RequestIpType.both);

        String ip = null;
        if (httpdnsResult.getIps() != null && httpdnsResult.getIps().length > 0) {
            ip = httpdnsResult.getIps()[0];
        } else if (httpdnsResult.getIpv6s() != null && httpdnsResult.getIpv6s().length > 0) {
            ip = httpdnsResult.getIpv6s()[0];
        }

        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            String newUrl = path.replaceFirst(url.getHost(), ip);
            conn = (HttpURLConnection) new URL(newUrl).openConnection();

            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            // 添加原有頭部信息
            if (headers != null) {
                for (Map.Entry<String, String> field : headers.entrySet()) {
                    conn.setRequestProperty(field.getKey(), field.getValue());
                }
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.getHost());

            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection)conn;
                // https場景,證書校驗(yàn)
                httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        String host = httpsURLConnection.getRequestProperty("Host");
                        if (null == host) {
                            host = httpsURLConnection.getURL().getHost();
                        }
                        return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
                    }
                });

                //TODO 在 SNI場景 部分介紹
            }

            //TODO 在 重定向 部分介紹
        } else {
            return null;
        }        

        
    } catch (MalformedURLException e) {
        Log.w(TAG, "recursiveRequest MalformedURLException");
    } catch (IOException e) {
        Log.w(TAG, "recursiveRequest IOException");
    } catch (Exception e) {
        Log.w(TAG, "unknow exception");
    }
    return null;
}

SNI場景

如果請求涉及到SNI場景,需要自定義SSLSocket,對SNI場景不熟悉的用戶可以參考SNI

自定義SSLSocket

class TlsSniSocketFactory constructor(conn: HttpsURLConnection): SSLSocketFactory() {
    private val mConn: HttpsURLConnection

    init {
        mConn = conn
    }

    override fun createSocket(plainSocket: Socket?, host: String?, port: Int, autoClose: Boolean): Socket {
        var peerHost = mConn.getRequestProperty("Host")
        if (peerHost == null) {
            peerHost = host
        }

        val address = plainSocket!!.inetAddress
        if (autoClose) {
            // we don't need the plainSocket
            plainSocket.close()
        }

        // create and connect SSL socket, but don't do hostname/certificate verification yet
        val sslSocketFactory =
            SSLCertificateSocketFactory.getDefault(0) as SSLCertificateSocketFactory
        val ssl = sslSocketFactory.createSocket(address, R.attr.port) as SSLSocket

        // enable TLSv1.1/1.2 if available
        ssl.enabledProtocols = ssl.supportedProtocols

        // set up SNI before the handshake
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            // setting sni hostname
            sslSocketFactory.setHostname(ssl, peerHost)
        } else {
            // No documented SNI support on Android <4.2, trying with reflection
            try {
                val setHostnameMethod = ssl.javaClass.getMethod(
                    "setHostname",
                    String::class.java
                )
                setHostnameMethod.invoke(ssl, peerHost)
            } catch (e: Exception) {
            }
        }

        // verify hostname and certificate
        val session = ssl.session

        if (!HttpsURLConnection.getDefaultHostnameVerifier()
                .verify(peerHost, session)
        ) throw SSLPeerUnverifiedException(
            "Cannot verify hostname: $peerHost"
        )

        return ssl
    }
}
public class TlsSniSocketFactory extends SSLSocketFactory {
    
    private HttpsURLConnection mConn;
    public TlsSniSocketFactory(HttpsURLConnection conn) {
        mConn = conn;
    }

    @Override
    public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException {
        String peerHost = mConn.getRequestProperty("Host");
        if (peerHost == null)
            peerHost = host;

        InetAddress address = plainSocket.getInetAddress();
        if (autoClose) {
            // we don't need the plainSocket
            plainSocket.close();
        }
        // create and connect SSL socket, but don't do hostname/certificate verification yet
        SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
        SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);

        // enable TLSv1.1/1.2 if available
        ssl.setEnabledProtocols(ssl.getSupportedProtocols());

        // set up SNI before the handshake
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            // setting sni hostname
            sslSocketFactory.setHostname(ssl, peerHost);
        } else {
            // No documented SNI support on Android <4.2, trying with reflection
            try {
                java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
                setHostnameMethod.invoke(ssl, peerHost);
            } catch (Exception e) {

            }
        }

        // verify hostname and certificate
        SSLSession session = ssl.getSession();

        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(peerHost, session))
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost);

        return ssl;
    }
}

設(shè)置自定義SSLSocket

fun recursiveRequest(
    path: String,
    headers: Map<String?, String?>?,
    reffer: String?
): URLConnection? {
    val conn: HttpURLConnection
    var url: URL? = null
    try {
        url = URL(path)
        // 同步接口獲取IP
        val httpdnsResult = HttpDns.getService(context, accountID)
            .getHttpDnsResultForHostSync(url.host, RequestIpType.both)
        var ip: String? = null
        if (httpdnsResult.ips != null && httpdnsResult.ips.isNotEmpty()) {
            ip = httpdnsResult.ips[0]
        } else if (httpdnsResult.ipv6s != null && httpdnsResult.ipv6s.isNotEmpty()) {
            ip = httpdnsResult.ipv6s[0]
        }
        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            val newUrl: String = path.replaceFirst(url.host, ip)
            conn = URL(newUrl).openConnection() as HttpURLConnection
            conn.connectTimeout = 30000
            conn.readTimeout = 30000
            conn.instanceFollowRedirects = false
            // 添加原有頭部信息
            headers?.forEach { entry ->
                conn.setRequestProperty(entry.key, entry.value)
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.host)
            if (conn is HttpsURLConnection) {
                // https場景,證書校驗(yàn)
                conn.hostnameVerifier = HostnameVerifier { _, session ->
                    var host = conn.getRequestProperty("Host")
                    if (null == host) {
                        host = conn.url.host
                    }
                    HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session)
                }

                // sni場景,創(chuàng)建SSLScocket
                conn.sslSocketFactory = TlsSniSocketFactory(conn)
            }

            //TODO 在 重定向 部分介紹
        } else {
            return null
        }
    } catch (e: MalformedURLException) {
        Log.w(TAG, "recursiveRequest MalformedURLException")
    } catch (e: IOException) {
        Log.w(TAG, "recursiveRequest IOException")
    } catch (e: Exception) {
        Log.w(TAG, "unknow exception")
    }
    return null
}
public URLConnection recursiveRequest(String path, Map<String, String> headers, String reffer) {
    HttpURLConnection conn;
    URL url = null;
    try {
        url = new URL(path);
        // 同步接口獲取IP
        HTTPDNSResult httpdnsResult = HttpDns.getService(context, accountID).getHttpDnsResultForHostSync(url.getHost(), RequestIpType.both);

        String ip = null;
        if (httpdnsResult.getIps() != null && httpdnsResult.getIps().length > 0) {
            ip = httpdnsResult.getIps()[0];
        } else if (httpdnsResult.getIpv6s() != null && httpdnsResult.getIpv6s().length > 0) {
            ip = httpdnsResult.getIpv6s()[0];
        }

        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            String newUrl = path.replaceFirst(url.getHost(), ip);
            conn = (HttpURLConnection) new URL(newUrl).openConnection();

            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            // 添加原有頭部信息
            if (headers != null) {
                for (Map.Entry<String, String> field : headers.entrySet()) {
                    conn.setRequestProperty(field.getKey(), field.getValue());
                }
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.getHost());

            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection)conn;
                // https場景,證書校驗(yàn)
                httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        String host = httpsURLConnection.getRequestProperty("Host");
                        if (null == host) {
                            host = httpsURLConnection.getURL().getHost();
                        }
                        return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
                    }
                });

                // sni場景,創(chuàng)建SSLScocket
                httpsURLConnection.setSSLSocketFactory(new TlsSniSocketFactory(httpsURLConnection));
            }

            //TODO 在 重定向 部分介紹
        } else {
            return null;
        }        
    } catch (MalformedURLException e) {
        Log.w(TAG, "recursiveRequest MalformedURLException");
    } catch (IOException e) {
        Log.w(TAG, "recursiveRequest IOException");
    } catch (Exception e) {
        Log.w(TAG, "unknow exception");
    }
    return null;
}

重定向

如果服務(wù)端返回重定向,此時需要判斷原有請求中是否含有cookie:

  • 如果原有請求報頭含有cookie,因?yàn)閏ookie是以域名為粒度進(jìn)行存儲的,重定向后cookie會改變,且無法獲取到新請求URL下的cookie,所以放棄攔截。

  • 如果不含cookie,重新發(fā)起二次請求。

fun recursiveRequest(
    path: String,
    headers: Map<String, String?>?,
    reffer: String?
): URLConnection? {
    val conn: HttpURLConnection
    var url: URL? = null
    try {
        url = URL(path)
        // 同步接口獲取IP
        val httpdnsResult = HttpDns.getService(context, accountID)
            .getHttpDnsResultForHostSync(url.host, RequestIpType.both)
        var ip: String? = null
        if (httpdnsResult.ips != null && httpdnsResult.ips.isNotEmpty()) {
            ip = httpdnsResult.ips[0]
        } else if (httpdnsResult.ipv6s != null && httpdnsResult.ipv6s.isNotEmpty()) {
            ip = httpdnsResult.ipv6s[0]
        }
        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            val newUrl = path.replaceFirst(url.host.toRegex(), ip!!)
            conn = URL(newUrl).openConnection() as HttpURLConnection
            conn.connectTimeout = 30000
            conn.readTimeout = 30000
            conn.instanceFollowRedirects = false
            // 添加原有頭部信息
            headers?.forEach { entry ->
                conn.setRequestProperty(entry.key, entry.value)
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.host)
            if (conn is HttpsURLConnection) {
                // https場景,證書校驗(yàn)
                conn.hostnameVerifier =
                    HostnameVerifier { _, session ->
                        var host = conn.getRequestProperty("Host")
                        if (null == host) {
                            host = conn.url.host
                        }
                        HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session)
                    }

                // sni場景,創(chuàng)建SSLScocket
                conn.sslSocketFactory = TlsSniSocketFactory(conn)
            }
        } else {
            return null
        }
        val code = conn.responseCode // Network block
        return if (code in 300..399) {
            // 原有報頭中含有cookie,放棄攔截
            var containCookie = false
            if (headers != null) {
                for (item in headers.keys) {
                    if (item.contains("Cookie")) {
                        containCookie = true
                        break
                    }
                }
            }
            
            if (containCookie) {
                return null
            }
            var location = conn.getHeaderField("Location")
            if (location == null) {
                location = conn.getHeaderField("location")
            }
            if (location != null) {
                if (!(location.startsWith("http://") || location
                        .startsWith("https://"))
                ) {
                    //某些時候會省略host,只返回后面的path,所以需要補(bǔ)全url
                    val originalUrl = URL(path)
                    location = (originalUrl.protocol + "://"
                            + originalUrl.host + location)
                }
                recursiveRequest(location, headers, path)
            } else {
                // 無法獲取location信息,讓瀏覽器獲取
                null
            }
        } else {
            // redirect finish.
            conn
        }
    } catch (e: MalformedURLException) {
        Log.w(TAG, "recursiveRequest MalformedURLException")
    } catch (e: IOException) {
        Log.w(TAG, "recursiveRequest IOException")
    } catch (e: Exception) {
        Log.w(TAG, "unknow exception")
    }
    return null
}
public URLConnection recursiveRequest(String path, Map<String, String> headers, String reffer) {
    HttpURLConnection conn;
    URL url = null;
    try {
        url = new URL(path);
        // 同步接口獲取IP
        HTTPDNSResult httpdnsResult = HttpDns.getService(context, accountID).getHttpDnsResultForHostSync(url.getHost(), RequestIpType.both);

        String ip = null;
        if (httpdnsResult.getIps() != null && httpdnsResult.getIps().length > 0) {
            ip = httpdnsResult.getIps()[0];
        } else if (httpdnsResult.getIpv6s() != null && httpdnsResult.getIpv6s().length > 0) {
            ip = httpdnsResult.getIpv6s()[0];
        }

        if (!TextUtils.isEmpty(ip)) {
            // 通過HTTPDNS獲取IP成功,進(jìn)行URL替換和HOST頭設(shè)置
            String newUrl = path.replaceFirst(url.getHost(), ip);
            conn = (HttpURLConnection) new URL(newUrl).openConnection();

            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            // 添加原有頭部信息
            if (headers != null) {
                for (Map.Entry<String, String> field : headers.entrySet()) {
                    conn.setRequestProperty(field.getKey(), field.getValue());
                }
            }
            // 設(shè)置HTTP請求頭Host域
            conn.setRequestProperty("Host", url.getHost());

            if (conn instanceof HttpsURLConnection) {
                final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) conn;
    
                // https場景,證書校驗(yàn)
                httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        String host = httpsURLConnection.getRequestProperty("Host");
                        if (null == host) {
                            host = httpsURLConnection.getURL().getHost();
                        }
                        return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
                    }
                });

                // sni場景,創(chuàng)建SSLScocket
                httpsURLConnection.setSSLSocketFactory(new TlsSniSocketFactory(httpsURLConnection));
            }
        } else {
            return null;
        }        

        int code = conn.getResponseCode();// Network block
        if (code >= 300 && code < 400) {
            // 原有報頭中含有cookie,放棄攔截
            boolean containCookie = false;
            if (headers != null) {
              for (Map.Entry<String, String> headerField : headers.entrySet()) {
                  if (headerField.getKey().contains("Cookie")) {
                      containCookie = true;
                      break;
                  }
              }
            }

            if (containCookie) {
                return null;
            }

            String location = conn.getHeaderField("Location");
            if (location == null) {
                location = conn.getHeaderField("location");
            }

            if (location != null) {
                if (!(location.startsWith("http://") || location
                        .startsWith("https://"))) {
                    //某些時候會省略host,只返回后面的path,所以需要補(bǔ)全url
                    URL originalUrl = new URL(path);
                    location = originalUrl.getProtocol() + "://"
                            + originalUrl.getHost() + location;
                }

                return recursiveRequest(location, headers, path);
            } else {
                // 無法獲取location信息,讓瀏覽器獲取
                return null;
            }
        } else {
            // redirect finish.
            return conn;
        }
    } catch (MalformedURLException e) {
        Log.w(TAG, "recursiveRequest MalformedURLException");
    } catch (IOException e) {
        Log.w(TAG, "recursiveRequest IOException");
    } catch (Exception e) {
        Log.w(TAG, "unknow exception");
    }
    return null;
}

MIME&Encoding

如果攔截網(wǎng)絡(luò)請求,需要返回一個WebResourceResponse

public WebResourceResponse(String mimeType, String encoding, InputStream data) ;

創(chuàng)建WebResourceResponse對象需要提供:

  • 請求的MIME類型

  • 請求的編碼

  • 請求的輸入流

其中請求輸入流可以通過URLConnection.getInputStream()獲取到,而MIME類型和encoding可以通過請求的ContentType獲取到,即通過URLConnection.getContentType(),如:

text/html;charset=utf-8

但并不是所有的請求都能得到完整的contentType信息,此時可以參考如下策略:

override fun shouldInterceptRequest(
    view: WebView?,
    request: WebResourceRequest?
): WebResourceResponse? {
    val scheme = request!!.url.scheme!!.trim()
    val method = request.method
    val headerFields = request.requestHeaders
    val url = request.url.toString()
    // 無法攔截body,攔截方案只能正常處理不帶body的請求;
    if ((scheme.equals("http", ignoreCase = true) || scheme.equals("https", ignoreCase = true))
        && method.equals("get", ignoreCase = true)
    ) {
        try {
            val connection = recursiveRequest(url, headerFields, null)
                ?: return super.shouldInterceptRequest(view, request)

            // 注*:對于POST請求的Body數(shù)據(jù),WebResourceRequest接口中并沒有提供,這里無法處理
            val contentType = connection.contentType
            var mime: String? = null
            val charset: String? = null
            if (contentType != null) {
                mime = contentType.split(";".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()[0]
                val fields = contentType.split(";".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                if (fields.size > 1) {
                    var charset = fields[1]
                    if (charset.contains("=")) {
                        charset = charset.substring(charset.indexOf("=") + 1)
                    }
                }
            }
            val httpURLConnection = connection as HttpURLConnection
            val statusCode = httpURLConnection.responseCode
            val response = httpURLConnection.responseMessage
            val headers = httpURLConnection.headerFields
            val headerKeySet: Set<String> = headers.keys

            // 無mime類型的請求不攔截
            return if (TextUtils.isEmpty(mime)) {
                super.shouldInterceptRequest(view, request)
            } else {
                // 二進(jìn)制資源無需編碼信息
                if (!TextUtils.isEmpty(charset) || (mime!!.startsWith("image")
                            || mime.startsWith("audio")
                            || mime.startsWith("video"))
                ) {
                    val resourceResponse =
                        WebResourceResponse(mime, charset, httpURLConnection.inputStream)
                    resourceResponse.setStatusCodeAndReasonPhrase(statusCode, response)
                    val responseHeader: MutableMap<String, String> = HashMap()
                    for (key in headerKeySet) {
                        // HttpUrlConnection可能包含key為null的報頭,指向該http請求狀態(tài)碼
                        responseHeader[key] = httpURLConnection.getHeaderField(key)
                    }
                    resourceResponse.responseHeaders = responseHeader
                    resourceResponse
                } else {
                    super.shouldInterceptRequest(view, request)
                }
            }
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    } 
    
    return super.shouldInterceptRequest(view, request)
}
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    String scheme = request.getUrl().getScheme().trim();
    String method = request.getMethod();
    Map<String, String> headerFields = request.getRequestHeaders();
    String url = request.getUrl().toString();
    // 無法攔截body,攔截方案只能正常處理不帶body的請求;
    if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
            && method.equalsIgnoreCase("get")) {
        try {
            URLConnection connection = recursiveRequest(url, headerFields, null);

            if (connection == null) {
                return super.shouldInterceptRequest(view, request);
            }

            // 注*:對于POST請求的Body數(shù)據(jù),WebResourceRequest接口中并沒有提供,這里無法處理
            String contentType = connection.getContentType();
            String mime = null;
            String charset = null;
            if (contentType != null) {
                mime = contentType.split(";")[0];

                String[] fields = contentType.split(";");
                if (fields.length > 1) {
                    String charset = fields[1];
                    if (charset.contains("=")) {
                        charset = charset.substring(charset.indexOf("=") + 1);
                    }
                }
            }
            
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            int statusCode = httpURLConnection.getResponseCode();
            String response = httpURLConnection.getResponseMessage();
            Map<String, List<String>> headers = httpURLConnection.getHeaderFields();
            Set<String> headerKeySet = headers.keySet();

            // 無mime類型的請求不攔截
            if (TextUtils.isEmpty(mime)) {
                return super.shouldInterceptRequest(view, request);
            } else {
                // 二進(jìn)制資源無需編碼信息
                if (!TextUtils.isEmpty(charset) || (mime.startsWith("image")
                        || mime.startsWith("audio")
                        || mime.startsWith("video"))) {
                    WebResourceResponse resourceResponse = new WebResourceResponse(mime, charset, httpURLConnection.getInputStream());
                    resourceResponse.setStatusCodeAndReasonPhrase(statusCode, response);
                    Map<String, String> responseHeader = new HashMap<String, String>();
                    for (String key : headerKeySet) {
                        // HttpUrlConnection可能包含key為null的報頭,指向該http請求狀態(tài)碼
                        responseHeader.put(key, httpURLConnection.getHeaderField(key));
                    }
                    resourceResponse.setResponseHeaders(responseHeader);
                    return resourceResponse;
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 
    return super.shouldInterceptRequest(view, request);
}

總結(jié)

場景

總結(jié)

不可用場景

  • API Level < 21的設(shè)備

  • POST請求

  • 無法獲取到MIME類型的請求

  • 無法獲取到編碼的非二進(jìn)制文件請求

可用場景

前提條件:

  • API Level >= 21

  • GET請求

  • 可以獲取到MIME類型以及編碼信息請求或是可以獲取到MIME類型的二進(jìn)制文件請求

可用場景:

  • 普通HTTP請求

  • HTTPS請求

  • SNI請求

  • HTTP報頭中不含cookie的重定向請求