11

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.

Altkey
  • 133
  • 1
  • 2
  • 6
  • I believe the `authorization` header should be lower case, and either set or add will work. Otherwise it seems like you might be having a problem with the API key. – Jonah Williams Mar 11 '18 at 01:08
  • Using cURL `Authorization` works, I tried using `authorization` in Flutter and that unfortunately didn't work. – Altkey Mar 11 '18 at 06:05
  • This will work -> `http.get(url, headers:{"Authorization":"value"}).then(.....)` – Daksh Gargas Aug 25 '18 at 11:42

3 Answers3

8

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',
});
Marcel
  • 8,831
  • 4
  • 39
  • 50
  • Also makes it lower case. I have the same issue. Putting in 'Authorization' results in lower caps 'authorization being written. By the way you can use the url: http://postman-echo.com/headers to get all the headers as the server sees it as a json response – Martin Kersten Nov 15 '19 at 20:15
1

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';
Goddard
  • 2,863
  • 31
  • 37
0

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.

Community
  • 1
  • 1
Durdu
  • 4,649
  • 2
  • 27
  • 47