Altkey
Altkey

Reputation: 133

Dart: HTTP GET with Header

I'm working on creating a Flutter application that works with LIFX. I'm trying to follow their instructions here, but I'm having issues adding a header to my HTTP GET request.

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';
      }

This returns with Error getting response: Http status 404. I've tried various ways of request.headers .set .add [HttpHeaders.Authorization] = "header" all return with a 404. Any advice would be appreciated.

Upvotes: 11

Views: 19716

Answers (3)

Goddard
Goddard

Reputation: 3059

In order to set headers you can't set the entire variable since it is set as final. What you need to do is set the value of the individual array items which are also known as the individual "headers" in this case.

For example :

http.Request request = http.Request('GET', uri);
request.headers['Authorization'] = 'Bearer $token';

Upvotes: 1

Durdu
Durdu

Reputation: 4849

I believe dart makes all the fields of a HttpHeader to lowercase.

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

The argument for that is because "Field names are case-insensitive". (otherwise it is not HTTP compliant)

https://www.rfc-editor.org/rfc/rfc2616#section-4.2

Let me know if you found a workaround for this.

Upvotes: 0

Marcel
Marcel

Reputation: 9569

You can pass a Map<String, String> to the http.get call as the headers parameter like this:

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

Upvotes: 11

Related Questions