【问题标题】:Flutter: How to add headers to http package in flutterFlutter:如何在 Flutter 中向 http 包添加标头
【发布时间】:2019-11-25 19:48:41
【问题描述】:

我正在尝试使用flutter包http调用以下API, 请求的结构是

GET /api/v3/4870020/products/123123?lang=en&token=123456789abcd HTTP/1.1
Host: app.ecwid.com
Content-Type: application/json;charset=utf-8
Cache-Control: no-cache

如何使用 http 包调用此 API。

【问题讨论】:

    标签: flutter get request


    【解决方案1】:

    您可以使用来自http 包的get()。试试这个:

      Future<void> fetchData(String lang, String token) async {
        final host = "app.ecwid.com"; // this is your baseUrl
        final apiPath = "api/v3/4870020/products/123123"; // which api do you want to use?
        final url = "https://$host/$apiPath?lang=$lang&token=$token"; // final url
        final response = await http.get(
          url,
          headers: {
            "Content-Type": "application/json",
            "Cache-Control": "no-cache"
          }
        );
    
        if(response.statusCode == 200) {
          // do some stuff with the received data.
        }
        else return;
      }
    

    如您所见,我们将语言和令牌参数指定到 url 的末尾。

    See the documentation

    【讨论】:

    • 谢谢@Firat
    【解决方案2】:

    您必须创建自己的客户端并覆盖发送方法以添加您的标头

    class HttpClient extends http.BaseClient {
        final http.Client _client = http.Client(); //your http client
    
        @override
        Future<http.StreamedResponse> send(http.BaseRequest request) {
            //add your headers in request here
            return this._client.send(request)
        }
    
    }
    

    【讨论】:

    • 感谢您的评论
    猜你喜欢
    • 1970-01-01
    • 2019-11-11
    • 2021-02-24
    • 2021-08-13
    • 2021-08-13
    • 2020-06-10
    • 2020-02-12
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多