Flutter中http请求抓包的完美解决方案
作者:Android进阶开发 发布时间:2023-08-22 18:47:47
前言
前阵子有同学反馈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);
}
_HttpClient类中_findProxyFromEnvironment方法的实现
static String _findProxyFromEnvironment(
Uri url, Map<String, String> environment) {
checkNoProxy(String option) {
if (option == null) return null;
Iterator<String> names = option.split(",").map((s) => s.trim()).iterator;
while (names.moveNext()) {
var name = names.current;
if ((name.startsWith("[") &&
name.endsWith("]") &&
"[${url.host}]" == name) ||
(name.isNotEmpty && url.host.endsWith(name))) {
return "DIRECT";
}
}
return null;
}
checkProxy(String option) {
if (option == null) return null;
option = option.trim();
if (option.isEmpty) return null;
int pos = option.indexOf("://");
if (pos >= 0) {
option = option.substring(pos + 3);
}
pos = option.indexOf("/");
if (pos >= 0) {
option = option.substring(0, pos);
}
// Add default port if no port configured.
if (option.indexOf("[") == 0) {
var pos = option.lastIndexOf(":");
if (option.indexOf("]") > pos) option = "$option:1080";
} else {
if (option.indexOf(":") == -1) option = "$option:1080";
}
return "PROXY $option";
}
// Default to using the process current environment.
if (environment == null) environment = _platformEnvironmentCache;
String proxyCfg;
String noProxy = environment["no_proxy"];
if (noProxy == null) noProxy = environment["NO_PROXY"];
if ((proxyCfg = checkNoProxy(noProxy)) != null) {
return proxyCfg;
}
if (url.scheme == "http") {
String proxy = environment["http_proxy"];
if (proxy == null) proxy = environment["HTTP_PROXY"];
if ((proxyCfg = checkProxy(proxy)) != null) {
return proxyCfg;
}
} else if (url.scheme == "https") {
String proxy = environment["https_proxy"];
if (proxy == null) proxy = environment["HTTPS_PROXY"];
if ((proxyCfg = checkProxy(proxy)) != null) {
return proxyCfg;
}
}
return "DIRECT";
}
从以上代码中可以发现代理配置从environment中读取,设置代理时必须指定http_proxy或https_proxy等。而从_openUrl方法实现中proxyConf = new _ProxyConfiguration(_findProxy(uri));
得出默认情况下environment是为空的,所以要想在Flutter的http请求中使用代理,则要指定相应的代理配置,即设置httpClient.findProxy的值。
示例代码:
_getHttpData() async {
var httpClient = new HttpClient();
httpClient.findProxy = (url) {
return HttpClient.findProxyFromEnvironment(url, environment: {"http_proxy": 'http://192.168.124.7:8888',});
};
var uri =
new Uri.http('t.weather.sojson.com', '/api/weather/city/101210101');
var request = await httpClient.getUrl(uri);
var response = await request.close();
if (response.statusCode == 200) {
print('请求成功');
var responseBody = await response.transform(Utf8Decoder()).join();
print('responseBody = $responseBody');
} else {
print('请求失败');
}
}
以上代码设置后即可使用Fiddler或Charles抓包了。
注:
代码中已设置代理,手机wifi不再需要进行代理设置;
192.168.124.7该IP为我们需要抓包的Charles所在电脑IP;
第二种抓包解决方案
如果使用Flutter写的APP不手动设置代理,则可以使用另一种方案来抓包。
通过电脑设置热点 -> 使用手机连接电脑热点上网 -> 在电脑上使用Wireshark抓数据包。
具体步骤如下(macOS系统下):
1. 打开系统偏好设置,找到“共享”
2. 打开“共享”,显示以下窗口,并选择共享以下来源的连接为指定的有线网络,用以下端口共享给电脑选择为Wi-Fi
3. 点击右下角Wi-Fi选项按钮,显示如下,填写对应信息后点击“好”保存
4. 回到刚才的“共享”窗口,打开左侧窗口中的服务“互联网共享”
5. 然后打开Wireshark软件界面,首页选择对应开热点的网络双击
6. 请求接口域名t.weather.sojson.com对应的IP为 58.222.18.24,则在上面输入框中输入请求过滤条件 "ip.dst == 58.222.18.24",然后通过手机APP发起网络请求
查看接口的IP地址
$ ping t.weather.sojson.com
PING nm.ctn.aicdn.com (58.222.18.24): 56 data bytes
64 bytes from 58.222.18.24: icmp_seq=0 ttl=54 time=16.792 ms
64 bytes from 58.222.18.24: icmp_seq=1 ttl=54 time=16.926 ms
64 bytes from 58.222.18.24: icmp_seq=2 ttl=54 time=15.804 ms
7. 选择对应的http请求,箭头指定行,右键点击,选择Follow->HTTP Stream选项
8. 弹出具体网络请求信息窗口如下
写在最后
本篇分享了两种Flutter中http数据包的抓包解决方案,大家可以根据实际情况来选择使用。
来源:https://www.jianshu.com/p/7bf51fddbb29


猜你喜欢
- 策略模式的应用场景策略模式是否要使用,取决于业务场景是否符合,有没有必要。是否符合如果业务是处于不同的场景时,采取不同的处理方式的话,就满足
- 一、国际化准备资源文件,资源文件的命名格式如下:baseName_language_country.propertiesbaseName_l
- 一、获取某年某月的天数1.在实现日期类的过程中,日期加减天数的应用场景一定会频繁使用到这个函数接口,因为加减天数会使得月份发生变化,可能增月
- 今天碰到一个非常奇怪的问题: 在Android中ImageView无法显示加载的本地SDCard图片。 具体过程是:先调用本地照相机程序摄像
- 定时的功能我们在手机上见得比较多,比如定时清理垃圾,闹钟,等等.定时功能在java中主要使用的就是Timer对象,他在内部使用的就是多线程的
- 在c和c++中,我们知道没办法起一个变量名叫int,因为这是C/C++保留的关键字,起这么一个变量名没办法区分到底是int类型还是int变量
- 作者: juky_huang 事件的简单解释: 事件是对象发送的消息,以发信号通知操作的发生。操作可能是由用户交互(例如
- 所以对于应用层用着还不是很方便。最近做一个项目顺便就封装了一个调用默认打印机的类。虽说有几个小bug,但对于目前来说,已经满足需求了。以后不
- 目录写在前面引入guava依赖包怎么做变量转换写在前面有时候需要处理对象属性的getter、setter方法,或者将属性与数据表字段进行相互
- 引言java 7提供了另外一个很有用的线程池框架,Fork/Join框架理论Fork/Join框架主要有以下两个类组成. * ForkJoi
- 在工作中,如果需要跟XML打交道,难免会遇到需要把一个类型集合转换成XML格式的情况。之前的方法比较笨拙,需要给不同的类型,各自写一个转换的
- 首先分析一下问题:其实这个红框不是android的bug,把编译模式从eng改成user就可以了,红框只是eng模式debug的时候提示你系
- 一、什么算异步?广义来讲,两个工作流能同时进行就算异步,例如,CPU与外设之间的工作流就是异步的。在面向服务的系统中,各个子系统之间通信一般
- 如果需要基于键对所需集合排序,就可以使用SortedList<TKey,TValue>类。这个类按照键给元素排序。这个集合中的值
- Git有很多可以配置的地方。比如,让Git显示颜色,会让命令输出看起来更醒目:$ git config --global color.ui
- Java 向上转型和向下转型的详解转型是在继承的基础上而言的,继承是面向对象语言中,代码复用的一种机制,通过继承,子类可以复用父
- 前言《飞机大战-I》是一款融合了街机、竞技等多种元素的经典射击手游。华丽精致的游戏画面,超炫带感的技能特效,超火爆画面让你肾上腺素爆棚,给你
- 大家好,这是 [C#.NET 拾遗补漏] 系列的第 08 篇文章,今天讲 C# 强大的 LINQ 查询。LINQ 是我最喜欢的 C# 语言特
- 项目中大多都会有很多的分类,且左右滑动,如美团首页(下图):不难发现包含2部分内容:1.左右滑动的页面,2.指示器。大度一般都会想到,vie
- idea中创建一个maven项目在pom文件中导入下面的依赖<!--mybatis核心包--> <depend