### MultipartRequest Usage Example Source: https://pub.dev/documentation/http/latest/http/MultipartRequest-class.html This example demonstrates how to create a MultipartRequest, add string fields and files, and send the request. ```APIDOC ## POST /example.com/create ### Description Sends a multipart/form-data request with string fields and files. ### Method POST ### Endpoint https://example.com/create ### Parameters #### Request Body - **user** (String) - Required - The user's email address. - **package** (File) - Required - The package file to upload (e.g., a .tar.gz file). ### Request Example ```dart var uri = Uri.https('example.com', 'create'); var request = http.MultipartRequest('POST', uri) ..fields['user'] = 'nweiz@google.com' ..files.add(await http.MultipartFile.fromPath( 'package', 'build/package.tar.gz', contentType: MediaType('application', 'x-tar'))); var response = await request.send(); if (response.statusCode == 200) print('Uploaded!'); ``` ### Response #### Success Response (200) Indicates that the upload was successful. #### Response Example ``` Uploaded! ``` ``` -------------------------------- ### Example Usage of StreamedRequest Source: https://pub.dev/documentation/http/latest/http/StreamedRequest-class.html An example demonstrating how to create and send a streamed HTTP request. ```APIDOC ## Example Usage of StreamedRequest ### Description This example shows how to send an HTTP POST request with a streaming body. ### Request Example ```dart final request = http.StreamedRequest('POST', Uri.http('example.com', '/')) ..contentLength = 10 ..sink.add([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // The sink must be closed to end the request. unawaited(request.sink.close()); final response = await request.send(); ``` ### Response Example (Response details would depend on the server's implementation) ``` -------------------------------- ### Example Usage of runWithClient Source: https://pub.dev/documentation/http/latest/http/runWithClient.html Demonstrates how to use runWithClient to provide a custom HTTP client for Android. The clientFactory is conditionally set based on the platform. ```dart class MyAndroidHttpClient extends BaseClient { @override Future send(http.BaseRequest request) { // your implementation here } } void main() { var clientFactory = Client.new; // Constructs the default client. if (Platform.isAndroid) { clientFactory = MyAndroidHttpClient.new; } runWithClient(myFunction, clientFactory); } void myFunction() { // Uses the `Client` configured in `main`. final response = await get(Uri.https('www.example.com', '')); final client = Client(); } ``` -------------------------------- ### Make Simple HTTP Requests with http Package Source: https://pub.dev/documentation/http/latest/index.html Use top-level functions for individual HTTP requests with minimal setup. Ensure necessary imports are included. ```dart import 'package:http/http.dart' as http; var url = Uri.https('example.com', 'whatsit/create'); var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'}); print('Response status: ${response.statusCode}'); print('Response body: ${response.body}'); print(await http.read(Uri.https('example.com', 'foobar.txt'))); ``` -------------------------------- ### GET Request Source: https://pub.dev/documentation/http/latest/http/get.html Sends an HTTP GET request with the given headers to the specified URL. This method initializes a new client for each request and closes it afterward. For multiple requests to the same server, consider using a single client. ```APIDOC ## GET / ### Description Sends an HTTP GET request with the given headers to the given URL. This automatically initializes a new Client and closes that client once the request is complete. If you're planning on making multiple requests to the same server, you should use a single Client for all of those requests. For more fine-grained control over the request, use Request instead. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **url** (Uri) - Required - The URL to send the GET request to. - **headers** (Map) - Optional - A map of headers to include in the request. ### Request Example ```dart Future get(Uri url, {Map? headers}) ``` ### Response #### Success Response (200) - **Response** (Response) - The HTTP response object. #### Response Example ```dart // Example response structure (actual content depends on the server) { "statusCode": 200, "body": "...", "headers": { ... } } ``` ``` -------------------------------- ### Implement HTTP GET Request Source: https://pub.dev/documentation/http/latest/http/get.html This function sends an HTTP GET request. It automatically manages a client for a single request. For multiple requests, reuse a client. ```dart Future get( Uri url, { Map? headers, }) Sends an HTTP GET request with the given headers to the given URL. This automatically initializes a new Client and closes that client once the request is complete. If you're planning on making multiple requests to the same server, you should use a single Client for all of those requests. For more fine-grained control over the request, use Request instead. ``` ```dart Future get(Uri url, {Map? headers}) => _withClient((client) => client.get(url, headers: headers)); ``` -------------------------------- ### GET /websites/pub_dev_http Source: https://pub.dev/documentation/http/latest/http/read.html Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a String. The Future will emit a ClientException if the response doesn't have a success status code. ```APIDOC ## GET /websites/pub_dev_http ### Description Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a String. The Future will emit a ClientException if the response doesn't have a success status code. ### Method GET ### Endpoint /websites/pub_dev_http ### Parameters #### Query Parameters - **url** (Uri) - Required - The URL to send the GET request to. - **headers** (Map) - Optional - A map of headers to include in the request. ### Request Example ```dart // Example usage (assuming you have a Uri object named 'myUrl') // final responseBody = await read(myUrl, headers: {'Authorization': 'Bearer YOUR_TOKEN'}); ``` ### Response #### Success Response (200) - **body** (String) - The body of the HTTP response as a String. #### Response Example ```json { "example": "This is the response body content." } ``` ### Error Handling - Emits a `ClientException` if the response status code is not successful. ``` -------------------------------- ### Test HTTP Requests Using a Mock Client Source: https://pub.dev/documentation/http/latest/index.html For testability, especially in Flutter, use a Client instance and mock it in tests. This example demonstrates mocking with `package:http/testing.dart`. ```dart // Instead of using static methods (harder to test): // var response = await http.get(Uri.https('example.com', 'data.json')); // Use a Client instance (easier to test): class DataService { final http.Client client; DataService({http.Client? client}) : client = client ?? http.Client(); Future fetchData() async { var response = await client.get(Uri.https('example.com', 'data.json')); return response.body; } } ``` ```dart import 'package:http/testing.dart'; import 'package:test/test.dart'; void main() { test('fetchData returns expected data', () async { final mockClient = MockClient((request) async { return http.Response('{"key": "value"}', 200); }); final dataService = DataService(client: mockClient); final result = await dataService.fetchData(); expect(result, '{"key": "value"}'); }); } ``` -------------------------------- ### Request Body Handling Source: https://pub.dev/documentation/http/latest/http/Request/body.html This section describes how to get and set the request body as a string. It also explains how the `Content-Type` header is managed automatically. ```APIDOC ## GET /request/body ### Description Retrieves the body of the request as a string. ### Method GET ### Endpoint /request/body ### Parameters None ### Response #### Success Response (200) - **body** (String) - The body of the request as a string. #### Response Example ```json { "body": "This is the request body content." } ``` ## SET /request/body ### Description Sets the body of the request as a string. If the `Content-Type` header is not already set, it will be added with `text/plain` and the appropriate charset. If the `Content-Type` is text-based or XML and lacks a charset, it will be updated with the encoding's charset. ### Method POST ### Endpoint /request/body ### Parameters #### Request Body - **body** (String) - Required - The string value to set as the request body. ### Request Example ```json { "body": "This is the new request body content." } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message indicating the body was set successfully. #### Response Example ```json { "message": "Request body set successfully." } ``` ``` -------------------------------- ### Define Platform-Specific HTTP Client Source: https://pub.dev/documentation/http/latest/index.html Use conditional imports to provide different HTTP client implementations for browser and native platforms. This example shows how to conditionally import a web-specific client. ```dart // -- http_client_factory.dart Client httpClient() { if (Platform.isAndroid) { return CronetClient.defaultCronetEngine(); } if (Platform.isIOS || Platform.isMacOS) { return CupertinoClient.defaultSessionConfiguration(); } return IOClient(); } ``` ```dart // -- http_client_factory_web.dart Client httpClient() => FetchClient(); ``` ```dart // -- main.dart import 'http_client_factory.dart' if (dart.library.js_interop) 'http_client_factory_web.dart' // The correct `httpClient` will be available. ``` -------------------------------- ### Accessing and Parsing HTTP Headers Source: https://pub.dev/documentation/http/latest/http/HeadersWithSplitValues/headersSplitValues.html Demonstrates how to retrieve and parse HTTP headers, with a focus on the `headersSplitValues` property which returns headers as a map of lowercase header names to a list of their values. Includes an example of parsing 'set-cookie' headers. ```APIDOC ## headersSplitValues Property ### Description Provides access to the HTTP headers returned by the server. Header names are converted to lowercase and stored with their associated header values. This property is useful for inspecting response headers, such as 'set-cookie'. ### Type `Map>` ### Usage Example ```dart import "dart:io"; import "package:http/http.dart"; void main() async { final response = await Client().get(Uri.https('example.com', '/')); final cookies = [ for (var value in response.headersSplitValues['set-cookie'] ?? []) Cookie.fromSetCookieValue(value) ]; print(cookies); } ``` ### Implementation Details The `headersSplitValues` getter processes the raw `headers` map. It splits header values containing commas into lists, with special handling for 'set-cookie' headers to correctly parse multiple cookies. ```dart Map> get headersSplitValues { var headersWithFieldLists = >{}; headers.forEach((key, value) { if (!value.contains(',')) { headersWithFieldLists[key] = [value]; } else { if (key == 'set-cookie') { headersWithFieldLists[key] = value.split(_setCookieSplitter); } else { headersWithFieldLists[key] = value.split(_headerSplitter); } } }); return headersWithFieldLists; } ``` ``` -------------------------------- ### MultipartFile Constructors Source: https://pub.dev/documentation/http/latest/http/MultipartFile-class.html Demonstrates how to create MultipartFile instances using different methods. ```APIDOC ## MultipartFile Constructors ### MultipartFile(String field, Stream> stream, int length, {String? filename, MediaType? contentType}) Creates a new MultipartFile from a chunked Stream of bytes. ### MultipartFile.fromBytes(String field, List value, {String? filename, MediaType? contentType}) Creates a new MultipartFile from a byte array. ### MultipartFile.fromString(String field, String value, {String? filename, MediaType? contentType}) Creates a new MultipartFile from a string. ``` -------------------------------- ### BrowserClient Constructors Source: https://pub.dev/documentation/http/latest/browser_client/BrowserClient-class.html Details on how to instantiate the BrowserClient. ```APIDOC ## Constructors ### BrowserClient() Creates a new instance of BrowserClient. ``` -------------------------------- ### GET Request Source: https://pub.dev/documentation/http/latest/http/Client/get.html Sends an HTTP GET request with the given headers to the specified URL. For more fine-grained control, use the send method. ```APIDOC ## GET /websites/pub_dev_http ### Description Sends an HTTP GET request with the given headers to the given URL. ### Method GET ### Endpoint /websites/pub_dev_http ### Parameters #### Query Parameters - **url** (Uri) - Required - The URL to send the GET request to. - **headers** (Map) - Optional - A map of headers to include in the request. ### Request Example ```dart // Example usage: // final response = await http.get(Uri.parse('https://example.com/data'), headers: {'Authorization': 'Bearer YOUR_TOKEN'}); ``` ### Response #### Success Response (200) - **Response** (Response) - The HTTP response object. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### BrowserClient Constructor Source: https://pub.dev/documentation/http/latest/browser_client/BrowserClient/BrowserClient.html Initializes a new instance of the BrowserClient class. ```APIDOC ## BrowserClient() ### Description Initializes a new instance of the BrowserClient class. ### Method Constructor ### Endpoint N/A ### Parameters None ### Request Example ``` BrowserClient() ``` ### Response #### Success Response (200) Initializes a BrowserClient object. #### Response Example ``` ``` ``` -------------------------------- ### Send HTTP GET Request Source: https://pub.dev/documentation/http/latest/http/Client/get.html Use this method to send an HTTP GET request. For more complex requests, consider using the 'send' method. ```dart Future get( Uri url, {Map? headers}, ) ``` ```dart Future get(Uri url, {Map? headers}); ``` -------------------------------- ### Client Constructor Source: https://pub.dev/documentation/http/latest/http/Client/Client.html Creates a new platform-appropriate client. It prioritizes `IOClient` if `dart:io` is available, then `BrowserClient` if `dart:js_interop` is available. If neither is available, it throws an unsupported error. ```APIDOC ## Client() ### Description Creates a new platform appropriate client. Creates an `IOClient` if `dart:io` is available and a `BrowserClient` if `dart:js_interop` is available, otherwise it will throw an unsupported error. ### Implementation ```dart factory Client() => zoneClient ?? createClient(); ``` ``` -------------------------------- ### Implement HTTP GET Request Source: https://pub.dev/documentation/http/latest/http/read.html Sends an HTTP GET request and returns the response body as a String. Emits a ClientException for non-success status codes. Automatically manages a new Client for each request. ```dart Future read(Uri url, {Map? headers}) => _withClient((client) => client.read(url, headers: headers)); ``` -------------------------------- ### MultipartFile Static Methods Source: https://pub.dev/documentation/http/latest/http/MultipartFile-class.html Details the static methods for creating MultipartFile instances. ```APIDOC ## MultipartFile Static Methods ### fromPath(String field, String filePath, {String? filename, MediaType? contentType}) → Future Creates a new MultipartFile from a path to a file on disk. ``` -------------------------------- ### HTTP GET Request - read method Source: https://pub.dev/documentation/http/latest/http/BaseClient/read.html The `read` method sends an HTTP GET request to a specified URL with optional headers. It returns the response body as a String and throws a ClientException for non-success status codes. ```APIDOC ## GET /websites/pub_dev_http ### Description Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a String. The Future will emit a ClientException if the response doesn't have a success status code. ### Method GET ### Endpoint /websites/pub_dev_http ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **body** (String) - The response body as a String. #### Response Example { "example": "Response body content" } ### Error Handling - **ClientException**: Thrown if the response status code is not a success code. ``` -------------------------------- ### Implement HTTP Read Method Source: https://pub.dev/documentation/http/latest/http/BaseClient/read.html This method sends an HTTP GET request and returns the response body as a String. It checks for successful status codes and throws a ClientException on failure. Use this for simple GET requests where only the body is needed. ```dart @override Future read(Uri url, {Map? headers}) async { final response = await get(url, headers: headers); _checkResponseSuccess(url, response); return response.body; } ``` -------------------------------- ### BrowserClient Class Overview Source: https://pub.dev/documentation/http/latest/browser_client/BrowserClient-class.html Provides an overview of the BrowserClient class, its inheritance, and limitations. ```APIDOC ## BrowserClient Class A `package:web`-based HTTP client that runs in the browser and is backed by `window.fetch`. This client inherits some limitations of `window.fetch`: * BaseRequest.persistentConnection is ignored; * Setting BaseRequest.followRedirects to `false` will cause ClientException when a redirect is encountered; * The value of BaseRequest.maxRedirects is ignored. Responses are streamed but requests are not. A request will only be sent once all the data is available. ### Inheritance * Object * BaseClient * BrowserClient ``` -------------------------------- ### Response Constructor Source: https://pub.dev/documentation/http/latest/http/Response/Response.html Creates a new HTTP response with a string body and other optional parameters. ```APIDOC ## Response Constructor ### Description Creates a new HTTP response with a string body. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **body** (String) - Required - The response body content. - **statusCode** (int) - Required - The HTTP status code. - **request** (BaseRequest?) - Optional - The originating request. - **headers** (Map) - Optional - A map of response headers. Defaults to an empty map. - **isRedirect** (bool) - Optional - Indicates if the response is a redirect. Defaults to false. - **persistentConnection** (bool) - Optional - Indicates if the connection should be persistent. Defaults to true. - **reasonPhrase** (String?) - Optional - The reason phrase for the status code. ### Request Example ```dart // Example of creating a Response object var response = Response("Hello, World!", 200, headers: {"content-type": "text/plain"}); ``` ### Response #### Success Response (200) This constructor does not directly return a response; it creates a Response object. #### Response Example ```json { "body": "Hello, World!", "statusCode": 200, "headers": {"content-type": "text/plain"}, "isRedirect": false, "persistentConnection": true, "reasonPhrase": null } ``` ``` -------------------------------- ### HTTP GET Request - Read Method Source: https://pub.dev/documentation/http/latest/http/Client/read.html Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a String. The Future will emit a ClientException if the response doesn't have a success status code. ```APIDOC ## GET /websites/pub_dev_http ### Description Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a String. The Future will emit a ClientException if the response doesn't have a success status code. ### Method GET ### Endpoint /websites/pub_dev_http ### Parameters #### Query Parameters - **url** (Uri) - Required - The URL to send the GET request to. - **headers** (Map) - Optional - A map of headers to include in the request. ### Request Example ```dart // Example usage: // final responseBody = await read(Uri.parse('https://example.com/data'), headers: {'Authorization': 'Bearer token'}); ``` ### Response #### Success Response (200) - **body** (String) - The response body as a String. #### Response Example ```json { "example": "This is the response body content." } ``` #### Error Handling - **ClientException**: Emitted if the response doesn't have a success status code. ``` -------------------------------- ### Getting bodyBytes from a Request Source: https://pub.dev/documentation/http/latest/http/Request/bodyBytes.html The bodyBytes getter returns the request body as a Uint8List. ```dart Uint8List get bodyBytes => _bodyBytes; ``` -------------------------------- ### Create and Configure IOClient Source: https://pub.dev/documentation/http/latest/io_client/IOClient/IOClient.html Instantiate an IOClient and configure its properties like user agent and idle timeout before passing it to the constructor. This allows for customized HTTP client behavior. ```dart final httpClient = HttpClient() ..userAgent = 'Book Agent' ..idleTimeout = const Duration(seconds: 5); final client = IOClient(httpClient); ``` -------------------------------- ### Create and Send a Multipart Request Source: https://pub.dev/documentation/http/latest/http/MultipartRequest-class.html Demonstrates how to create a MultipartRequest with string fields and a file, then send it. Ensure the file path is correct and the server endpoint is valid. ```dart var uri = Uri.https('example.com', 'create'); var request = http.MultipartRequest('POST', uri) ..fields['user'] = 'nweiz@google.com' ..files.add(await http.MultipartFile.fromPath( 'package', 'build/package.tar.gz', contentType: MediaType('application', 'x-tar'))); var response = await request.send(); if (response.statusCode == 200) print('Uploaded!'); ``` -------------------------------- ### Get Persistent Connection Source: https://pub.dev/documentation/http/latest/http/BaseRequest/persistentConnection.html Retrieves the current state of the persistent connection. Defaults to true. ```dart bool get persistentConnection => _persistentConnection; ``` -------------------------------- ### Get maxRedirects Source: https://pub.dev/documentation/http/latest/http/BaseRequest/maxRedirects.html Retrieves the current maximum number of redirects allowed. Defaults to 5. ```dart int get maxRedirects => _maxRedirects; ``` -------------------------------- ### MediaType Constructor Source: https://pub.dev/documentation/http/latest/http/MediaType/MediaType.html This snippet details the constructor for the MediaType class, outlining its parameters and how it initializes the object. ```APIDOC ## MediaType Constructor ### Description Constructs a new MediaType object with the given type, subtype, and optional parameters. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **type** (String) - Required - The main type of the media (e.g., 'application', 'text'). - **subtype** (String) - Required - The subtype of the media (e.g., 'json', 'html'). - **parameters** (Map) - Optional - A map of additional parameters for the media type. ### Request Example ```dart MediaType('application', 'json', {'charset': 'utf-8'}) ``` ### Response #### Success Response (200) N/A (This is a constructor, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### MultipartFile Methods Source: https://pub.dev/documentation/http/latest/http/MultipartFile-class.html Lists the methods available for the MultipartFile class. ```APIDOC ## MultipartFile Methods ### finalize() → ByteStream ### noSuchMethod(Invocation invocation) → dynamic Invoked when a nonexistent method or property is accessed. ### toString() → String A string representation of this object. ``` -------------------------------- ### Get followRedirects Value Source: https://pub.dev/documentation/http/latest/http/BaseRequest/followRedirects.html Retrieves the current value of the followRedirects property. Defaults to true. ```dart bool get followRedirects => _followRedirects; ``` -------------------------------- ### Get contentLength Source: https://pub.dev/documentation/http/latest/http/Request/contentLength.html This getter returns the size of the request body in bytes. It is automatically calculated from bodyBytes. ```dart @override int get contentLength => bodyBytes.length; ``` -------------------------------- ### Create Platform-Appropriate Client Source: https://pub.dev/documentation/http/latest/http/Client/Client.html Use this factory constructor to create a new client. It automatically selects an IOClient or BrowserClient based on platform availability. Ensure the necessary dart:io or dart:js_interop libraries are available. ```dart factory Client() => zoneClient ?? createClient(); ``` -------------------------------- ### runWithClient Implementation Source: https://pub.dev/documentation/http/latest/http/runWithClient.html The core implementation of the runWithClient function, utilizing Dart's runZoned to set up a zone with a custom client factory. ```dart R runWithClient(R Function() body, Client Function() clientFactory, {ZoneSpecification? zoneSpecification}) => runZoned(body, zoneValues: {#_clientToken: Zone.current.bindCallback(clientFactory)}, zoneSpecification: zoneSpecification); ``` -------------------------------- ### Get isFinalized Property Source: https://pub.dev/documentation/http/latest/http/MultipartFile/isFinalized.html Returns a boolean indicating if finalize has been called. This is part of the implementation details. ```dart bool get isFinalized => _isFinalized; ``` -------------------------------- ### Get mimeType Property Source: https://pub.dev/documentation/http/latest/http/MediaType/mimeType.html Returns the media type's MIME type. This is a getter that concatenates the type and subtype. ```dart String get mimeType => '$type/$subtype'; ``` -------------------------------- ### Build App Bundle with No Default HTTP Client Source: https://pub.dev/documentation/http/latest/index.html Use the `no_default_http_client` build flag to prevent the default HTTP client from being included, reducing application size. This is useful when you provide your own client. ```bash $ flutter build appbundle --dart-define=no_default_http_client=true ... ``` -------------------------------- ### Get contentLength Property Source: https://pub.dev/documentation/http/latest/http/BaseRequest/contentLength.html Retrieves the current value of the contentLength. This getter returns the size of the request body in bytes. ```dart int? get contentLength => _contentLength; ``` -------------------------------- ### Adding Fetch Client Dependency Source: https://pub.dev/documentation/http/latest/index.html Command to add the `fetch_client` package as a dependency to a Dart project using `dart pub add`. ```bash # Replace "fetch_client" with the package that you want to use. dart pub add fetch_client ``` -------------------------------- ### Get Finalized Status Source: https://pub.dev/documentation/http/latest/http/BaseRequest/finalized.html Returns the current state of the finalized property. This getter is used to check if the finalize operation has been invoked. ```dart bool get finalized => _finalized; ``` -------------------------------- ### RetryClient Constructors Source: https://pub.dev/documentation/http/latest/retry/RetryClient-class.html Information on how to instantiate the RetryClient. ```APIDOC ## RetryClient Constructors ### RetryClient Creates a client wrapping `_inner` that retries HTTP requests. **Parameters** - `_inner` (Client) - The underlying HTTP client to wrap. - `retries` (int, optional) - The maximum number of retries. Defaults to 3. - `when` (FutureOr(BaseResponse), optional) - A function to determine if a response should trigger a retry. Defaults to `_defaultWhen`. - `whenError` (FutureOr(Object, StackTrace), optional) - A function to determine if an error should trigger a retry. Defaults to `_defaultWhenError`. - `delay` (Duration(int), optional) - A function to calculate the delay between retries. Defaults to `_defaultDelay`. - `onRetry` (FutureOr(BaseRequest, BaseResponse?, int), optional) - A callback function executed before each retry. ### RetryClient.withDelays Like RetryClient.new, but with a pre-computed list of `delays` between each retry. **Parameters** - `inner` (Client) - The underlying HTTP client to wrap. - `delays` (Iterable) - An iterable of durations specifying the delay between retries. - `when` (FutureOr(BaseResponse), optional) - A function to determine if a response should trigger a retry. Defaults to `_defaultWhen`. - `whenError` (FutureOr(Object, StackTrace), optional) - A function to determine if an error should trigger a retry. Defaults to `_defaultWhenError`. - `onRetry` (FutureOr(BaseRequest, BaseResponse?, int), optional) - A callback function executed before each retry. ``` -------------------------------- ### Compiling with no_default_http_client Source: https://pub.dev/documentation/http/latest/http/runWithClient.html Shows how to compile a Dart executable with the no_default_http_client flag to potentially reduce binary size. This flag affects Client() factory calls outside the runWithClient zone. ```bash $ dart compile exe --define=no_default_http_client=true ... ``` -------------------------------- ### POST /websites/pub_dev_http/send Source: https://pub.dev/documentation/http/latest/retry/RetryClient/send.html Sends an HTTP request and asynchronously returns the response. Implementers should call BaseRequest.finalize to get the body of the request as a ByteStream. ```APIDOC ## POST /websites/pub_dev_http/send ### Description Sends an HTTP request and asynchronously returns the response. Implementers should call BaseRequest.finalize to get the body of the request as a ByteStream. They shouldn't make any assumptions about the state of the stream; it could have data written to it asynchronously at a later point, or it could already be closed when it's returned. Any internal HTTP errors should be wrapped as ClientExceptions. ### Method POST ### Endpoint /websites/pub_dev_http/send ### Parameters #### Request Body - **request** (BaseRequest) - Required - The HTTP request object to send. ### Request Example ```json { "example": "BaseRequest object" } ``` ### Response #### Success Response (200) - **streamedResponse** (StreamedResponse) - The asynchronous response to the HTTP request. #### Response Example ```json { "example": "StreamedResponse object" } ``` ``` -------------------------------- ### Get Form-Encoded Body Fields Source: https://pub.dev/documentation/http/latest/http/Request/bodyFields.html Accesses form-encoded fields from a request body. Throws a `StateError` if the request's `Content-Type` is not `application/x-www-form-urlencoded`. ```dart Map get bodyFields { var contentType = _contentType; if (contentType == null || contentType.mimeType != 'application/x-www-form-urlencoded') { throw StateError('Cannot access the body fields of a Request without ' 'content-type "application/x-www-form-urlencoded".'); } return Uri.splitQueryString(body, encoding: encoding); } ``` -------------------------------- ### Initialize MultipartRequest Source: https://pub.dev/documentation/http/latest/http/MultipartRequest/MultipartRequest.html Use this constructor to create a new MultipartRequest instance. It requires the HTTP method and the URL for the request. ```dart MultipartRequest( super.method, super.url ); ``` -------------------------------- ### POST /websites/pub_dev_http Source: https://pub.dev/documentation/http/latest/http/BaseRequest/send.html The send method sends an HTTP request. It initializes a new Client and closes it upon completion. For multiple requests to the same server, it's recommended to reuse a single Client. ```APIDOC ## POST /websites/pub_dev_http ### Description Sends this request. This automatically initializes a new Client and closes that client once the request is complete. If you're planning on making multiple requests to the same server, you should use a single Client for all of those requests. ### Method POST ### Endpoint /websites/pub_dev_http ### Parameters ### Request Body ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **stream** (StreamedResponse) - The response stream. - **statusCode** (int) - The HTTP status code. - **contentLength** (int) - The length of the content. - **request** (Request) - The original request. - **headers** (Map) - The response headers. - **isRedirect** (bool) - Whether the response is a redirect. - **url** (Uri) - The URL of the response. - **persistentConnection** (bool) - Whether the connection is persistent. - **reasonPhrase** (String) - The reason phrase for the status code. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### BaseClient Methods Source: https://pub.dev/documentation/http/latest/http/BaseClient-class.html This section details the methods available on the BaseClient class, including HTTP request methods and utility methods. ```APIDOC ## BaseClient Methods ### close() Sends an HTTP DELETE request with the given headers to the given URL. ### Method `void` ### Description Closes the client and cleans up any resources associated with it. ### delete(Uri url, {Map? headers, Object? body, Encoding? encoding}) Sends an HTTP DELETE request with the given headers to the given URL. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the DELETE request to. #### Query Parameters None #### Request Body - **body** (Object) - Optional - The request body. - **encoding** (Encoding) - Optional - The encoding for the request body. ### get(Uri url, {Map? headers}) Sends an HTTP GET request with the given headers to the given URL. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the GET request to. #### Query Parameters None #### Request Body None ### head(Uri url, {Map? headers}) Sends an HTTP HEAD request with the given headers to the given URL. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the HEAD request to. #### Query Parameters None #### Request Body None ### patch(Uri url, {Map? headers, Object? body, Encoding? encoding}) Sends an HTTP PATCH request with the given headers and body to the given URL. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the PATCH request to. #### Query Parameters None #### Request Body - **body** (Object) - Optional - The request body. - **encoding** (Encoding) - Optional - The encoding for the request body. ### post(Uri url, {Map? headers, Object? body, Encoding? encoding}) Sends an HTTP POST request with the given headers and body to the given URL. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the POST request to. #### Query Parameters None #### Request Body - **body** (Object) - Optional - The request body. - **encoding** (Encoding) - Optional - The encoding for the request body. ### put(Uri url, {Map? headers, Object? body, Encoding? encoding}) Sends an HTTP PUT request with the given headers and body to the given URL. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the PUT request to. #### Query Parameters None #### Request Body - **body** (Object) - Optional - The request body. - **encoding** (Encoding) - Optional - The encoding for the request body. ### read(Uri url, {Map? headers}) Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a String. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the GET request to. #### Query Parameters None #### Request Body None ### readBytes(Uri url, {Map? headers}) Sends an HTTP GET request with the given headers to the given URL and returns a Future that completes to the body of the response as a list of bytes. ### Method `Future` ### Parameters #### Path Parameters - **url** (Uri) - Required - The URL to send the GET request to. #### Query Parameters None #### Request Body None ### send(BaseRequest request) Sends an HTTP request and asynchronously returns the response. ### Method `Future` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (BaseRequest) - Required - The HTTP request to send. ``` -------------------------------- ### Implement HTTP Send Method Source: https://pub.dev/documentation/http/latest/testing/MockClient/send.html Implementers should call BaseRequest.finalize to get the body of the request as a ByteStream. Any internal HTTP errors should be wrapped as ClientExceptions. ```dart @override Future send(BaseRequest request) async { var bodyStream = request.finalize(); return await _handler(request, bodyStream); } ``` -------------------------------- ### Request Implementation Source: https://pub.dev/documentation/http/latest/http/Request/Request.html Details the internal implementation of the Request constructor, including default encoding and body initialization. ```APIDOC ## Request Implementation ### Description This section details the internal implementation of the Request constructor, including the initialization of default encoding and the request body. ### Method Constructor Implementation ### Endpoint N/A ### Parameters None ### Request Example ```dart // This is an internal implementation detail and not directly called by the user. // Example of how it's used internally: Request( 'POST', Uri.parse('https://example.com/api/submit'), ) // ... internal initialization happens here ... ; ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Response Constructor Implementation Source: https://pub.dev/documentation/http/latest/http/Response/Response.html Provides the implementation for the Response constructor, which initializes a new HTTP response. It uses an internal `bytes` constructor after encoding the body string. ```dart Response(String body, int statusCode, {BaseRequest? request, Map headers = const {}, bool isRedirect = false, bool persistentConnection = true, String? reasonPhrase}) : this.bytes(_encodingForHeaders(headers).encode(body), statusCode, request: request, headers: headers, isRedirect: isRedirect, persistentConnection: persistentConnection, reasonPhrase: reasonPhrase); ``` -------------------------------- ### Get Request Body as String Source: https://pub.dev/documentation/http/latest/http/Request/body.html Retrieves the request body as a decoded string. This uses the configured encoding. If the Content-Type is not set, it defaults to text/plain. ```dart String get body => encoding.decode(bodyBytes); ``` -------------------------------- ### toString Method Source: https://pub.dev/documentation/http/latest/http/MediaType/toString.html Converts the media type to a string, producing a valid HTTP media type. ```APIDOC ## toString Method ### Description Converts the media type to a string. This will produce a valid HTTP media type. ### Method N/A (This is a method within a class, not a standalone API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (String) - **Output** (string) - A string representation of the media type. #### Response Example ``` application/json; charset="utf-8" ``` ``` -------------------------------- ### MediaType Implementation Source: https://pub.dev/documentation/http/latest/http/MediaType/MediaType.html Shows the implementation of the MediaType constructor, converting type and subtype to lowercase and handling parameters. ```dart MediaType(String type, String subtype, [Map? parameters]) : type = type.toLowerCase(), subtype = subtype.toLowerCase(), parameters = UnmodifiableMapView( parameters == null ? {} : CaseInsensitiveMap.from(parameters)); ``` -------------------------------- ### HTTP Request Functions Source: https://pub.dev/documentation/http/latest/http Provides functions for making common HTTP requests like GET, POST, PUT, DELETE, PATCH, HEAD, and reading response bodies. ```APIDOC ## HTTP Request Functions ### Description These functions provide convenient ways to send HTTP requests and retrieve responses. ### Functions - **delete(Uri url, {Map? headers, Object? body, Encoding? encoding})** → Future Sends an HTTP DELETE request. - **get(Uri url, {Map? headers})** → Future Sends an HTTP GET request. - **head(Uri url, {Map? headers})** → Future Sends an HTTP HEAD request. - **patch(Uri url, {Map? headers, Object? body, Encoding? encoding})** → Future Sends an HTTP PATCH request. - **post(Uri url, {Map? headers, Object? body, Encoding? encoding})** → Future Sends an HTTP POST request. - **put(Uri url, {Map? headers, Object? body, Encoding? encoding})** → Future Sends an HTTP PUT request. - **read(Uri url, {Map? headers})** → Future Sends an HTTP GET request and returns the response body as a String. - **readBytes(Uri url, {Map? headers})** → Future Sends an HTTP GET request and returns the response body as a list of bytes. ``` -------------------------------- ### Create a Custom HTTP Client with Extended Behavior Source: https://pub.dev/documentation/http/latest/index.html Subclass BaseClient to wrap an existing Client and add custom behavior, such as setting a User-Agent header for all outgoing requests. ```dart class UserAgentClient extends http.BaseClient { final String userAgent; final http.Client _inner; UserAgentClient(this.userAgent, this._inner); @override Future send(http.BaseRequest request) { request.headers['user-agent'] = userAgent; return _inner.send(request); } } ``` -------------------------------- ### Get Sink Property Implementation Source: https://pub.dev/documentation/http/latest/http/StreamedRequest/sink.html This code shows how to access the sink property, which is used to write data to the request body. The data is buffered and sent when the request is completed. ```dart StreamSink> get sink => _controller.sink; ``` -------------------------------- ### Response.bytes Constructor Source: https://pub.dev/documentation/http/latest/http/Response/Response.bytes.html Creates a new HTTP response with a byte array body. ```APIDOC ## Response.bytes Constructor ### Description Create a new HTTP response with a byte array body. ### Method Constructor ### Parameters - **bodyBytes** (List) - Required - The byte array representing the response body. - **statusCode** (int) - Required - The HTTP status code of the response. - **request** (BaseRequest?) - Optional - The request that generated this response. - **headers** (Map) - Optional - A map of HTTP headers. Defaults to an empty map. - **isRedirect** (bool) - Optional - Indicates if the response is a redirect. Defaults to false. - **persistentConnection** (bool) - Optional - Indicates if the connection should be persistent. Defaults to true. - **reasonPhrase** (String?) - Optional - The reason phrase for the status code. ### Request Example ```dart // Example of creating a Response.bytes object final response = Response.bytes( [72, 101, 108, 108, 111], // 'Hello' in bytes 200, headers: {'content-type': 'text/plain'} ); ``` ### Response #### Success Response (200) - **bodyBytes** (Uint8List) - The byte array body of the response. - **statusCode** (int) - The HTTP status code. - **request** (BaseRequest?) - The request that generated this response. - **headers** (Map) - The HTTP headers. - **isRedirect** (bool) - Indicates if the response is a redirect. - **persistentConnection** (bool) - Indicates if the connection should be persistent. - **reasonPhrase** (String?) - The reason phrase for the status code. #### Response Example ```json { "bodyBytes": [72, 101, 108, 108, 111], "statusCode": 200, "headers": {"content-type": "text/plain"}, "isRedirect": false, "persistentConnection": true, "reasonPhrase": null } ``` ``` -------------------------------- ### Get HTTP Response Body as String Source: https://pub.dev/documentation/http/latest/http/Response/body.html Access the response body as a decoded string. Decoding uses the charset from the Content-Type header, with fallbacks for unknown or missing encoding. ```dart String get body => _encodingForHeaders(headers).decode(bodyBytes); ``` -------------------------------- ### Get contentLength Source: https://pub.dev/documentation/http/latest/http/MultipartRequest/contentLength.html This getter calculates the total length of a multipart request body. It sums the lengths of all fields and files, including boundary markers and headers. It cannot be set manually. ```dart @override int get contentLength { var length = 0; fields.forEach((name, value) { length += '--'.length + _boundaryLength + '\r\n'.length + utf8.encode(_headerForField(name, value)).length + utf8.encode(value).length + '\r\n'.length; }); for (var file in files) { length += '--'.length + _boundaryLength + '\r\n'.length + utf8.encode(_headerForFile(file)).length + file.length + '\r\n'.length; } return length + '--'.length + _boundaryLength + '--\r\n'.length; } ``` -------------------------------- ### Create a Mock HTTP Client Source: https://pub.dev/documentation/http/latest/testing Use MockClient to replace http.Client in tests. It takes a handler function that intercepts requests and returns mock responses. Ensure your handler correctly routes requests or returns appropriate errors. ```dart import 'dart:convert'; import 'package:http/testing.dart'; var client = MockClient((request) async { if (request.url.path != "/data.json") { return Response("", 404); } return Response( json.encode({ 'numbers': [1, 4, 15, 19, 214] }), 200, headers: {'content-type': 'application/json'}); }); ``` -------------------------------- ### Get Encoding Source: https://pub.dev/documentation/http/latest/http/Request/encoding.html Retrieves the encoding used for the request. It checks the Content-Type header for a charset parameter; otherwise, it uses the default encoding. Reading with an unknown charset throws a FormatException. ```dart Encoding get encoding { if (_contentType == null || !_contentType!.parameters.containsKey('charset')) { return _defaultEncoding; } return requiredEncodingForCharset(_contentType!.parameters['charset']!); } ```