Search code examples
dartserverhttprequest

How to make an OPTIONS request in Dart?


If I use the HttpClient or http library I can make GET, POST, PUT, DELETE and other requests, but I don't see anything for making an OPTIONS request. I can't even figure out how to send a generic request by typing in the method name as a string. The reason I want it is for testing my server that gets OPTIONS requests sometimes.

This is how I make a POST request:

final response = await http.post(url, headers: postHeaders, body: postBody);

How would I make an OPTIONS request?


Solution

  • It is possible to do like so:

    import 'package:http/http.dart';
    
    final client = Client();
    final method = 'OPTIONS';
    final url = Uri.parse('http://www.example.com');
    final request = Request(method, url);
    final streamedResponse = await client.send(request);
    final response = await Response.fromStream(streamedResponse);
    print(response.statusCode);