前言
前阵子有同学反馈Flutter中的http请求无法通过fiddler抓包,作者喜欢使用Charles抓包工具,于是抽时间写了个小demo测试了一下,结论是在手机上设置代理,Charles确实抓不到请求数据包。于是对该问题进行了分析:
-
确定使用的是http发起的get请求,理论上http协议应该可以被Charles抓到包的,如果没有抓到包,那可能是没有走代理,于是乎通过将笔记本连接的wifi断开测试了一下手机上APP发起http请求,发现请求成功,证实确实没有走代理;
-
为什么http请求没有通过wifi走代理呢,因为之前安卓原生使用的一些http框架都是正常走代理的啊,那是不是有可能代码中有api方法可以设置请求不走代理,于是乎就研读了一下Flutter中http相关的源码,最终找到了答案。
http请求源码跟踪
http.dart中的HttpClient是一个抽象类,成员方法的具体实现在http_impl.dart中,http的get请求实现如下:
Future<HttpClientRequest> getUrl(Uri url) => _openUrl("get", url);
Future<_HttpClientRequest> _openUrl(String method, Uri uri) {
.
.
.
// Check to see if a proxy server should be used for this connection.
var proxyConf = const _ProxyConfiguration.direct();
if (_findProxy != null) {
// TODO(sgjesse): Keep a map of these as normally only a few
// configuration strings will be used.
try {
proxyConf = new _ProxyConfiguration(_findProxy(uri));
} catch (error, stackTrace) {
return new Future.error(error, stackTrace);
}
}
return _getConnection(uri.host, port, proxyConf, isSecure)
.then((_ConnectionInfo info) {
.
.
.
});
}
首先,我们可以发现方法中有一行注释// Check to see if a proxy server should be used for this connection.
,意思是“检查是否应该使用代理服务器进行此连接”;
然后,有一个proxyConf
对象初始化和根据_findProxy
来创建新的proxyConf对象的语句,然后通过_getConnection(uri.host, port, proxyConf, isSecure)
来创建连接,_getConnection的源码如下:
Future<_ConnectionInfo> _getConnection(String uriHost, int uriPort,
_ProxyConfiguration proxyConf, bool isSecure) {
Iterator<_Proxy