(Flutter) HTTPClient无效参数:URI中未指定主机

27

我目前正在开发一个小应用程序,允许用户查看存储在Heroku上的数据库。但是,在使用数据库的URL:".herokuapp.com/api/"时,我遇到了上述问题。

var client = createHttpClient();
var response = await client.read('<example>.herokuapp.com/api/<data>');
List data = JSON.decode(response);

看起来Heroku没有使用HTTP(S)或www,我认为后者可能是问题所在。

有人知道我如何绕过或解决这个问题吗?


如果您使用浏览器、curl或wget访问URL会发生什么? - Günter Zöchbauer
我不确定wgetcurl是什么,但浏览器可以正常工作。 - Oscar Cooke-Abbott
wgetcurl 是用于进行 HTTP 请求的命令行工具。在浏览器开发者工具中,网络请求的 URL 是什么样子的呢? - Günter Zöchbauer
我之前试过找,但没找到,那我应该在哪里准确地找到它呢? - Oscar Cooke-Abbott
很不幸,老实说,在过去的几个月里发生了太多事情,我甚至都记不得这是关于什么的 :/ - Oscar Cooke-Abbott
显示剩余2条评论
9个回答

56

我知道这是一个老问题,但我刚刚遇到了这个问题,并通过在URL前添加"http://"来解决它。


15

其中一个问题是在API URL前没有添加"http://";

解决方案 在API URL前添加"http://" 例如 API_URL = "api.openweathermap.org/data/2.5/weather?q={city%20name}&appid={your%20api%20key}"

通过添加"http://",变成 "http://api.openweathermap.org/data/2.5/weather?q={city%20name}&appid={your%20api%20key}"


8
如果您在最新版本的Flutter中仍然遇到此问题,请尝试检查以下事项。
以前,uri是一个String类型,现在已更改为Uri类型,用于处理http请求。
如果我们尝试使用URL作为:
String urlPath = '<example>.herokuapp.com/api/<data>';
client.read(Uri(path: urlPath));

我们将会得到异常信息No host specified in URI

可以通过在Uri类中使用parse方法来解决

client.read(Uri.parse(urlPath));

它解决了这个问题。


2
不错!对我有用! - Erick Filho

4

这对我起作用。

child: CircleAvatar(
      backgroundImage: imageFile != null
          ? FileImage(imageFile)
          : imgUrl.isNotEmpty
              ? NetworkImage(imgUrl)
              : null,),

2

这对我很有用

CachedNetworkImage(imageUrl:  'https://example.com/'+item['image'],),

1
这与之前的答案有何不同?之前的答案不仅展示了相同的解决方案,而且还对其进行了解释,并且更直接地与原始问题相关。 - user643011

1

在你的URL之前,只需添加http://即可。

来自:

 192.168.2.101/test/login

至:

 http://192.168.2.101/test/login

1

如果您在同一页上显示图像,请始终指定图像路径的默认值,尝试将此添加到您的小部件中:

  child: Image.network(
     valueOrDefault<String>(                                              
      listViewDocumentsRecord.docImageUrl,                                             
      'https://picsum.photos/seed/513/600',
       ),
            


0

您需要按照URI语法将URL分解为以下内容:

对于普通的非安全URL:

final httpUri = Uri(
    scheme: 'http',
    host: 'dart.dev',
    path: 'guides/libraries/library-tour',
    fragment: 'numbers');
print(httpUri); // http://dart.dev/guides/libraries/library-tour#numbers

对于安全的URL:

final httpsUri = Uri(
    scheme: 'https',
    host: 'dart.dev',
    path: 'guides/libraries/library-tour',
    fragment: 'numbers');
print(httpsUri); // https://dart.dev/guides/libraries/library-tour#numbers

对于电子邮件URL,请使用以下内容:

final mailtoUri = Uri(
    scheme: 'mailto',
    path: 'John.Doe@example.com',
    queryParameters: {'subject': 'Example'});
print(mailtoUri); // mailto:John.Doe@example.com?subject=Example

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接