Flutter:如何在Flutter中向HTTP包添加标题

时间:2019-11-25 19:48:41

标签: flutter get request

我正在尝试使用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。

2 个答案:

答案 0 :(得分:1)

您必须创建自己的客户端并重写send方法以添加标头

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)
    }

}

答案 1 :(得分:1)

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

  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