【问题标题】:Flutter http.get with path parameter issue带有路径参数问题的 Flutter http.get
【发布时间】:2019-10-25 11:38:31
【问题描述】:

如果我尝试在 Postman 上运行,它可以完美运行。看下图。

可以看到,下面是url

https://xx.yy/api/user/:slug

路径参数是

蛞蝓

我在 Flutter 中的代码,不起作用!

    final _authority = "xx.yy";
    final _path = "api/user/:slug"; // Tried to replace "api/user/slug" AND "api/user"
    final _params = { "slug" : "govadiyo" };
    final _uri =  Uri.https(_authority, _path, _params);

    print(Uri.encodeFull(_uri.toString()));
    var response = await http.get(Uri.encodeFull(_uri.toString()), headers: {'Content-Type': 'application/json'});
    print(response.body);

上面的代码有什么问题吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    2021 年像这样在 http.get() 中发送数据的最佳方式 您可以发送任何类型的数据,如 Map、String 任何您想要的类型,只需将数据放入 sendNotification 参数中

    http://www.google.com/hitnotification?sender_name=fahad&email=fahad@gmail.com&receiver_id=2`
    
    
     String sendNotification = "your data";
    
    final uri = Uri.http('www.google.com','/hitnotification'+sendNotification);
    
           await http.get(uri);
    

    【讨论】:

      【解决方案2】:

      正如您正确注意到的,您需要一个路径变量,而不是查询参数(这意味着您的变量成为 url 的一部分)。

      您可以使用字符串插值将变量放入 url(实际上,串联也可以)。该变量可能包含需要编码的字符。

      final slug = 'govadiyo';
      final url = Uri.encodeFull('api/user/${slug}');
      print(url);
      

      【讨论】:

        【解决方案3】:

        看看这个答案。看来问题和你的差不多: https://stackoverflow.com/a/52824562/11620670

        去掉 _path 变量中的参数。

        _uri 变量似乎结构良好。

        经过这个小改动后,它应该可以工作了。链接答案中的示例也是如此。

        问候

        【讨论】:

        • 感谢您的回答,但很抱歉,我尝试了这个但结果相同,在我的问题中,我已经拆分了主机和路径。
        • @Govaadiyo 你把主机和路径分开了,它完全没问题。我的意思是,您将 _path 更改为 api/user 而没有 /:slug。您在 _params 中很好地定义了您的参数。我认为这只是路径的问题。你的路径在你的第一个打印声明中说了什么?
        • 我根据您的建议删除并打印为“xx.yy/api/user?slug=govadio”,但无法正常工作:(好奇地在 Postman 上工作,但不在 dart 中。感谢您提供任何其他方式的帮助?
        猜你喜欢
        • 2015-01-25
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多