Dart:带头的HTTP GET

时间:2018-03-10 19:53:36

标签: http dart flutter lifx

我正在创建一个适用于LIFX的Flutter应用程序。我正在尝试按照他们的说明here,但我在向HTTP GET请求添加标头时遇到问题。

TestHttpGet() async {
  var httpClient = new HttpClient();
  var header = "Bearer $token"; //token hidden
  var url = 'https://api.lifx.com/v1/lights/all/state';

  String result;
  try {
    var request = await httpClient.getUrl(Uri.parse(url));
    request.headers.set("Authorization", header);
    var response = await request.close();
    if (response.statusCode == HttpStatus.OK) {
          var json = await response.transform(UTF8.decoder).join();
          print(json);
          var data = JSON.decode(json);
          result = data['brightness'].toString();
        } else {
          result =
              'Error getting response:\nHttp status ${response.statusCode}';
        }
      } catch (exception) {
        result = 'Failed parsing response';
      }

返回Error getting response: Http status 404。我已经尝试了request.headers .set .add [HttpHeaders.Authorization] = "header"以404的方式返回的各种方式。任何建议都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

您可以将Map<String, String>作为http.get参数传递给headers调用,如下所示:

await httpClient.get(url, headers: {
  'Authorization': 'Bearer $token',
});

答案 1 :(得分:0)

我相信dart可以使HttpHeader的所有字段都变为小写。

https://github.com/flutter/flutter/issues/16665

该参数的原因是“字段名称不区分大小写”。 (否则,它不符合HTTP标准)

https://tools.ietf.org/html/rfc2616#section-4.2

如果您找到了解决方法,请告诉我。