前陣子有同窗反饋Flutter中的http請求沒法經過fiddler抓包,做者喜歡使用Charles抓包工具,因而抽時間寫了個小demo測試了一下,結論是在手機上設置代理,Charles確實抓不到請求數據包。因而對該問題進行了分析:編程
肯定使用的是http發起的get請求,理論上http協議應該能夠被Charles抓到包的,若是沒有抓到包,那多是沒有走代理,因而乎經過將筆記本鏈接的wifi斷開測試了一下手機上APP發起http請求,發現請求成功,證明確實沒有走代理;json
爲何http請求沒有經過wifi走代理呢,由於以前安卓原生使用的一些http框架都是正常走代理的啊,那是否是有可能代碼中有api方法能夠設置請求不走代理,因而乎就研讀了一下Flutter中http相關的源碼,最終找到了答案。api
http.dart中的HttpClient是一個抽象類,成員方法的具體實如今http_impl.dart中,http的get請求實現以下:bash
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
的默認值async
Function _findProxy = HttpClient.findProxyFromEnvironment;
複製代碼
HttpClient類中findProxyFromEnvironment
方法的實現ide
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系統下):
查看接口的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
複製代碼
本篇分享了兩種Flutter中http數據包的抓包解決方案,你們能夠根據實際狀況來選擇使用。若是有其餘Flutter相關的問題,歡迎你們經過公衆號發消息留言。
說明:
文章轉載自對應的「Flutter編程指南」微信公衆號,更多Flutter相關技術文章打開微信掃描二維碼關注微信公衆號獲取。