【问题标题】:Flutter: Not able to make HTTP-GET requestFlutter:无法发出 HTTP-GET 请求
【发布时间】:2019-05-07 23:33:07
【问题描述】:

我的代码如下所示:

HttpClient client = new HttpClient();
  client.get('192.168.4.1', 80, '/').then((HttpClientRequest req) {
    print(req.connectionInfo);
    return req.close();
  }).then((HttpClientResponse rsp) {
  print(rsp);
});

我正在尝试在没有互联网连接的本地 wifi 网络中发出 HTTP-Get 请求,但我总是收到以下错误:

E/flutter (8386): [ERROR:flutter/shell/common/shell.cc(184)] Dart 错误:未处理的异常: E/flutter (8386): SocketException: Connection failed (OS Error: Network is unreachable, errno = 101), address = 192.168.4.1, port = 80 E/颤振(8386):#0 _rootHandleUncaughtError。 (dart:async/zone.dart:1112:29) E/flutter (8386):#1 _microtaskLoop (dart:async/schedule_microtask.dart:41:21) E/flutter (8386): #2 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

我使用的是安卓设备。

【问题讨论】:

  • 这是在调试版本还是发布版本中?
  • 这是一个调试版本
  • stackoverflow.com/questions/2378607/… 应该默认启用调试版本
  • 尝试重新启动模拟器,有时模拟器上的连接会出现错误。在模拟器上的网页上测试
  • 尝试添加192.168.4.1而不是只添加ip

标签: android flutter


【解决方案1】:

颤动

我可以像这样从 Flutter 发出 http GET 请求:

String androidEmulatorLocalhost = 'http://10.0.2.2:3000';
Response response = await get(androidEmulatorLocalhost);
String bodyText = response.body;

这需要import 'package:http/http.dart';

服务器

这是我在本地运行的Node.js server

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

另见

【讨论】:

  • 您不必在 android 模拟器上引用代理 localhost IP 地址,而只需将端口从主机转发(“反向”)到 android 模拟器。因此,如果您的应用程序需要访问的服务器在 localhost:3000 上运行,您可以在终端中执行 adb reverse tcp:3000 tcp:3000,并且您应该能够从您的 android 模拟器访问位于 localhost:3000 的主机服务器,因此能够从 Flutter 应用程序中使用 localhost:3000 引用该服务器。
猜你喜欢
  • 1970-01-01
  • 2014-08-15
  • 2019-08-27
  • 2019-08-15
  • 2022-01-18
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2019-11-30
相关资源
最近更新 更多