darthttp-headersbasic-authenticationdartpad

Dartpad make request with basic auth


How to make a basic auth request against httpbin.org/basic-auth using

with dartpad. This is my dartpad-demo-code

What is working

Using get() finally works

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

void main(List<String> arguments) async {

  final url_httpbin = Uri.https('httpbin.org', '/basic-auth/myuser/mypasswd');  
  
  var base64Encoder = convert.Base64Encoder(); 
  var creds64 = base64Encoder.convert('myuser:mypasswd'.codeUnits);
  Map<String, String> authHeader = {'Authorization':'Basic $creds64'};  
    
  final response = await http.get(url_httpbin, 
       headers: authHeader); // sending headers with basic auth

  if (response.statusCode == 200) {
    final jsonResponse = convert.jsonDecode(response.body);
    print('Repsonse $jsonResponse');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

Question How can Request be used

My attempt to use the Request() class fails

var request = http.Request('GET', url_httpbin);
request.headers(authHeader); // <-- error 

The last line returns

Error compiling to JavaScript: lib/main.dart:23:18: Error: 'headers' isn't a function or method and can't be invoked.
request.headers(authHeader); ^^^^^^^ Error: Compilation failed.

Or this

 request.headers = authHeader; // error 

Results in

Error compiling to JavaScript: lib/main.dart:23:11: Error: The setter 'headers' isn't defined for the class 'Request'.

  • 'Request' is from 'package:http/src/request.dart' ('/app/local_pub_cache/hosted/pub.dev/http-1.1.0/lib/src/request.dart'). request.headers = authHeader; ^^^^^^^ Error: Compilation failed.

From the Request class documentation it is unclear to me how i can use the class to make an http request.


Solution

  • To set the headers using Request you need to fill the map returned by Request.headers, for example:

    request.headers['HeaderName'] = 'Value';
    

    then to send it you need to call Client.send on an instance of Client to send the request, which will returned a StreamedResponse (meaning that the body is not known in advance); you can then get a Response using Response.fromStream.

    Here is a full example:

      final client = Client();
      final request = Request('GET', url_httpbin);
    
      request.headers['HeaderName'] = 'Value';
    
      final streamedResponse = await client.send(request);
      final response = await Response.fromStream(streamedResponse);
    
      // Do your stuff ...
      
      client.close();