如何在Flutter中使用Dart http包指向localhost:8000? [英] How to point to localhost:8000 with the Dart http package in Flutter?

查看:384
本文介绍了如何在Flutter中使用Dart http包指向localhost:8000?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照 Flutter Networking/HTTP教程向在我的服务器上运行的服务器发出GET请求本地主机:8000.通过我的浏览器访问我的本地主机工作正常.我的代码如下:

I'm following the Flutter Networking/HTTP tutorial to do a GET request to a server running on my localhost:8000. Visiting my localhost via my browser works fine. My code looks like this:

var url = 'http://localhost:8000';
Future<String> getUnits(String category) async {
    var response = await httpClient.get('$url/$category');
    return response.body;
}

当我指向任何实际URL(例如https://example.com)时,此方法工作正常,但是当我指向https://localhost:8000https://localhost(或这些的任何变体)时,出现以下错误:

This works fine when I point to any real URL, such as https://example.com, but when I point to https://localhost:8000 or https://localhost (or any variations of these), I get an error starting with:

E/flutter ( 4879): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 4879): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 47060
E/flutter ( 4879): #0      IOClient.send (package:http/src/io_client.dart:30:23)

每次我重新加载应用程序时,上述错误中的端口都会更改.我查看了 http程序包代码,似乎没有一种方法可以指定URL的端口.我如何指向我的本地主机?

The port in the error above changes each time I reload the app. I looked in the http package code and it doesn't seem like there is a way to specify the port for the URL. How do I point to my localhost?

推荐答案

简短答案:您可以传递Uri而不是字符串作为参数

Short answer: You can pass an Uri instead of a string as parameter

      var client = createHttpClient();
      client.get(new Uri.http("locahost:8000", "/category"));

这篇关于如何在Flutter中使用Dart http包指向localhost:8000?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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