Flutter:无法发出HTTP-GET请求

时间:2018-12-06 09:48:05

标签: android flutter

我的代码如下:

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);
});

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

  

E / flutter(8386):[错误:flutter / shell / common / shell.cc(184)] Dart错误:未处理的异常:   E / flutter(8386):SocketException:连接失败(OS错误:网络无法访问,errno = 101),地址= 192.168.4.1,端口= 80   E / flutter(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)

我正在使用Android设备。

1 个答案:

答案 0 :(得分:0)

颤振

我可以像这样从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}/`);
});

另请参见