对127.0.0.1:80的HTTP请求失败 [英] HTTP request to 127.0.0.1:80 fails

查看:316
本文介绍了对127.0.0.1:80的HTTP请求失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境

  • Android Studio最新版本
  • 运行Android Nougat的Android模拟器
  • MAMP用作HTTP服务器

问题

我的简单方法

  Future<String> _getSimpleReply( String command, callback, errorCallback ) async {

    try {

      HttpClientRequest request = await _myClient.get( '127.0.0.1', 80 '/' );
      HttpClientResponse response = await request.close();
      await callback( response.toString() );

    } on SocketException catch( e ) {

      errorCallback( e.toString() );

    }

  }

失败,并显示错误:

cbLoginFailed :: SocketException: OS Error: 
  Connection refused, errno = 111, address = 127.0.0.1, port = 46414

当前使用已配置为可访问互联网的Android模拟器:

Currently using the Android emulator, which has been configured for internet access:

<uses-permission android:name="android.permission.INTERNET"/>

出于测试目的,HTTP服务器是MAMP,如果我在浏览器中输入以下链接,它将执行index.php脚本并返回一些简单的字符串:

For test purpose, the HTTP server is MAMP, which executes the index.php script and returns some simple string, if I enter this link in a browser:

http://127.0.0.1/index.php

如果我用localhost替换127.0.0.1,情况不会改变.

The situation does not change, if I replace 127.0.0.1 with localhost.

但是,如果我确实使用有效的公共FQDN 更改了127.0.0.1,则该方法可以正常工作:

But if I do change 127.0.0.1 with a valid public FQDN, the method works just fine:

doLoginSuccess :: Instance of '_HttpClientResponse'

问题

  1. 为什么Android模拟器/Flutter/Dart处理的127.0.0.1与有效的FQDN?

  1. Why does the android emulator / flutter / dart handles 127.0.0.1 different than a valid FQDN?

以及如何更改此行为?

推荐答案

第一个注释指出,localhost或127.0.0.1是-在Android模拟器上运行应用程序时-实际上是本地计算机,Android应用正在执行.就Android应用而言,本地计算机是模拟的Android系统.

As pointed out by the first comment, localhost or 127.0.0.1 is - when running an app on Android emulator - in fact the local machine on which the Android app is executing. With respect of the Android app, the local machine is the emulated Android system.

因此,颤动代码中的http请求根本不会离开模拟器.由于Flutter应用程序不提供HTTP服务器,因此模拟器拒绝了http请求.

Therefore, the http request from the flutter code doesn't leave the emulator at all. Since the Flutter app doesn't provide a HTTP Server, the emulator refuses the http request.

需要更改为正在执行模拟器的主机的地址.

Android模拟器使用特殊的IP地址与其主机或主机网关进行通信.

The Android emulator uses special IP addresses to communicate with its host or the host gateway.

请查看 Android文档.

例如,主机的环回接口由以下IP标识: 10.0.2.2 因此,如果通常使用 127.0.0.1:80 ,则可以用 10.0.2.2:80 代替.

E.g., the host‘s loopback Interface is identified by this IP: 10.0.2.2 So, if normally one would use 127.0.0.1:80, one can substitute it with 10.0.2.2:80.

这篇关于对127.0.0.1:80的HTTP请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆