Flutter HTTP request using Basic Auth + passing user and password to receive user data back

3,534

Your credentials should be in base64. You can visit the SO post in the comment.

Your code should be look like this:

main() async {
  String username = 'user';
  String password = 'pass';
  String basicAuth =
      'Basic ' + base64Encode(utf8.encode('$username:$password'));
  print(basicAuth);

  Response r = await get('https://www.adresse/login.php',
      headers: <String, String>{'authorization': basicAuth});
  print(r.statusCode);
  print(r.body);
}

See also this blog post.

Share:
3,534
Bernard
Author by

Bernard

Updated on December 11, 2022

Comments

  • Bernard
    Bernard over 1 year

    I am a newcomer, not a professional coder (so be gentle), trying to build a Flutter app that must connect to a web/server API in HTTP. According to the doc, to make a connection a header must be used, this header uses the Basic Ath method, with login and password + a content type. Till that point I think I have found how to do (see code snippet hereunder) but I have to send a user id and a user password to the API in order to receive back user data. And I must humbly confess that I am stuck there... I thank you in advance for your help! Bernard

    My code (after importing dart:convert et package:http/http.dart + installed the required dependencies) :

    void brol() async {
    String username = 'user';
    String password = 'pass';
    String userpass = '$username:$password';
    String basicAuth =
    'Basic ' + userpass;
    print(basicAuth);
    Response r = await get('https://www.adresse/login.php',
    headers: {'authorization': basicAuth});
    }
    

    Many Thanks in advance for your answer, Bernard