如何在flutter中发出本地http请求?

Vin*_*ais 0 django flutter

我正在制作一个应用程序,并且我已经在本地运行了一台服务器。我可以通过我的导航器访问网址:

Request URL: http://localhost:4444/categorie?page_size=15&page=1
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:4444
Referrer Policy: no-referrer-when-downgrade
Run Code Online (Sandbox Code Playgroud)

预览:

{
    "count": 4,
    "next": null,
    "previous": null,
    "results": [
        {
            "uid": "_b656062d3754",
            "name": "Pinga"
        },
        {
            "uid": "_0c644473c244",
            "name": "Cerveja"
        },
        {
            "uid": "_75df557ccbaa",
            "name": "Vinhos"
        },
        {
            "uid": "_8e32ce3baded",
            "name": "Refrigerantes"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试颤动时,请求从不响应:

getCategories() async {

  String url = 'http://localhost:4444/categorie?page_size=15&page=1';

  var response = await http.get(url);

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return response.body;
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

Run Code Online (Sandbox Code Playgroud)

我跑我的服务器Windows10使用Django。我的颤振应用程序正在Android Studio使用Virtual Machine作为设备。我尝试将 ip 更改为127.0.0.110.0.0.1但仍然无法正常工作。我是否更改了 Django 的主机或在我的颤振中或内部启用了任何配置VirutalBox

  • 对其他站点的请求运行良好。问题出在本地。

我的依赖:

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  http: any

dev_dependencies:
  flutter_test:
    sdk: flutter
Run Code Online (Sandbox Code Playgroud)

Joã*_*res 5

您 PC 上的本地主机与 Android 模拟器上的不同。要从 Android 模拟器访问 PC 的本地主机,您需要指向10.0.2.2.

这意味着您需要将代码更改为:

String url = 'http://10.0.2.2:4444/categorie?page_size=15&page=1';
Run Code Online (Sandbox Code Playgroud)