Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 291
Altkey Avatar asked Mar 10 '18 19:03

Altkey


2 Answers

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',
});
like image 99
Marcel Avatar answered Nov 12 '22 22:11

Marcel


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';
like image 1
Goddard Avatar answered Nov 12 '22 22:11

Goddard