没有合适的资源?快使用搜索试试~ 我知道了~
首页Flutter中http请求抓包的完美解决方案
资源详情
资源评论
资源推荐

Flutter中中http请求抓包的完美解决方案请求抓包的完美解决方案
主要给大家介绍了关于Flutter中http请求抓包的完美解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者使用
Flutter具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
前言前言
前阵子有同学反馈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> proxies = proxyConf.proxies.iterator;
Future<_ConnectionInfo> connect(error) {
if (!proxies.moveNext()) return new Future.error(error);
_Proxy proxy = proxies.current;
String host = proxy.isDirect ? uriHost : proxy.host;
int port = proxy.isDirect ? uriPort : proxy.port;
return _getConnectionTarget(host, port, isSecure)
.connect(uriHost, uriPort, proxy, this)
// On error, continue with next proxy.
.catchError(connect);
}
return connect(new HttpException("No proxies given"));
}
从代码中我们可以看到根据代理配置信息来将请求的host和port进行重置,然后创建真实的连接。
跟踪以上源码我们发现dart中http请求是否走代理是需要配置的,而_findProxy变量和配置的代理信息有关。
http__impl.dart文件中的_HttpClient类中定义了_findProxy的默认值
Function _findProxy = HttpClient.findProxyFromEnvironment;
HttpClient类中findProxyFromEnvironment方法的实现
static String findProxyFromEnvironment(Uri url,
{Map<String, String> environment}) {
HttpOverrides overrides = HttpOverrides.current;
if (overrides == null) {
return _HttpClient._findProxyFromEnvironment(url, environment);
}
return overrides.findProxyFromEnvironment(url, environment);
}
















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0