3

My code looks like this:

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

I'm trying to make a HTTP-Get request in the local wifi-network, that has no internet-connection, but I always get the following Error:

E/flutter ( 8386): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception: E/flutter ( 8386): SocketException: Connection failed (OS Error: Network is unreachable, errno = 101), address = 192.168.4.1, port = 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)

I'm using an android device.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
philippG777
  • 137
  • 2
  • 6

1 Answers1

2

Flutter

I am able to make an http GET request from Flutter like this:

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

which requires import 'package:http/http.dart';.

Server

Here is my Node.js server running locally:

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

See also

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    You don't have to refer to the proxy localhost IP address on the android emulator, instead you can just forward ("reverse") the port from the host machine to the android emulator. So if the server that your app needs to reach is running on localhost:3000, you can do `adb reverse tcp:3000 tcp:3000` in your terminal, and you should be able access the host server at localhost:3000 from your android emulator, and therefore be able to refer to that server with localhost:3000 from your Flutter app. – Filip Petrovic Sep 05 '20 at 22:16