我正在遵循Flutter Networking / HTTP教程对运行在localhost:8000上的服务器进行GET请求。通过浏览器访问我的本地主机可以正常工作。我的代码如下所示:
var url = 'http://localhost:8000'; Future<String> getUnits(String category) async { var response = await httpClient.get('$url/$category'); return response.body; }
当我指向任何真实的网址(例如)时,此方法工作正常https://example.com,但是当我指向https://localhost:8000或https://localhost(或它们的任何变体)时,出现以下错误:
https://example.com
https://localhost:8000
https://localhost
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的端口。我如何指向我的本地主机?
简短答案:您可以传递Uri而不是字符串作为参数
var client = createHttpClient(); client.get(new Uri.http("locahost:8000", "/category"));