w_transport library

Platform-agnostic transport library for sending and receiving data over HTTP and WebSocket. HTTP support includes plain-text, JSON, form-data, and multipart data, as well as custom encoding. WebSocket support includes native WebSockets in the browser and the VM with the option to use SockJS in the browser.

import 'package:w_transport/w_transport.dart';

HTTP

To send HTTP requests, there are two options. For simple plain-text requests, the static methods on the Http can be used.

Response response = await Http.get(Uri.parse('/ping'));

These static methods on Http require a URI but also take headers and a plain-text body.

Alternatively, there are several request classes available that offer a greater amount of control and help with sending different types of data:

  • Plain-text request: Request

  • JSON request: JsonRequest

  • FormRequest: FormRequest

  • MultipartRequest: MultipartRequest

    // Plain-text request - supports plain-text body as a String or bytes. // content-type: text/plain Request request = new Request();

    // JSON request - supports a Map or List as the request body. // content-type: application/json JsonRequest request = new JsonRequest();

    // Form request - supports sending a Map of form fields // content-type: application/www-form-urlencoded FormRequest request = new FormRequest();

    // Multipart request - supports sending a request with several parts, // consisting of text fields and/or files. MultipartRequest request = new MultipartRequest();

Each one of these requests shares the exact same API (see BaseRequest) for everything that doesn't pertain to the request body. The request body API is tailored to the type of request.

When sending a request, there are two options that dictate the type of response that will be returned. The default request dispatch methods (get(), post(), 'put(), etc.) return a Future` that resolves with an instance of Response. This response object provides synchronous access to the complete response body as plain-text, as bytes, or as JSON (if decodable).

If the response body is exceptionally large or if you'd prefer to deal with the response body in a streamed format, there are a set of request dispatch methods that will return a Future that resolves with an instance of StreamedResponse. These methods are the same as the above, with "stream" prepended (streamGet(), streamPost(), streamPut(), etc.). This response object provides synchronous access to the response metadata (status code, headers, etc.), but do not load the entire response body into memory. Instead, the response body is available as a stream of chunks of bytes.

WebSocket

The WebSocket API mirrors the dart:io WebSocket class, but works for both client and server usage. If you've used the server-side WebSocket, this is almost exactly the same.

To establish a WebSocket connection, use the static connect() method:

Uri wsUri = Uri.parse('ws://echo.websocket.org');
WSocket webSocket = await WSocket.connect(wsUri);

Once connected, add items to the WebSocket like a sink to send data to the server, and listen to it like a stream to receive data from the server.

Classes

AdvancedBackOffCalculator
Use this class to calculate exponential backoff with jitter.
BaseRequest
A common API that applies to all request types. The piece that is missing is that which is specific to the request body. Setting the request body differs based on the type of request being sent (plain-text, JSON, form, multipart, or streamed). As such, that piece of the API is delegated to the specific request classes.
BaseResponse
Client
An HTTP client acts as a single point from which many requests can be constructed. All requests constructed from a client will inherit headers, the withCredentials flag, and the timeoutThreshold.
FinalizedRequest
A finalized, read-only representation of a request.
FormRequest
Representation of an HTTP request where the request body is a form that will be encoded as a url query string.
GlobalWebSocketMonitor
Http
Static methods for quickly sending HTTP requests.
HttpBody
Representation of an HTTP request body or an HTTP response body.
HttpClient
An HTTP client acts as a single point from which many requests can be constructed. All requests constructed from a client will inherit headers, the withCredentials flag, and the timeoutThreshold.
HttpInterceptor
Base class representing an interceptor that can be registered with a HttpClient instance to intercept HTTP requests and responses in order to modify or augment them prior to dispatch and delivery, respectively.
JsonRequest
Representation of an HTTP request where the request body is a json-encodable Map or List.
MediaType
A class representing an HTTP media type, as used in Accept and Content-Type headers.
MultipartFile
A platform-independent file abstraction. The MultipartRequest accepts files of this type.
MultipartRequest
Representation of an HTTP request where the request body is comprised of one or more parts. Each part can be either a field name and value or a file.
Request
Representation of an HTTP request where the request body is plain-text.
RequestPayload
Representation of a request payload. Currently only contains the request instance, but may contain more contextual information in the future.
RequestProgress
A representation of a progress event at a specific point in time either for an HTTP request upload or download. Based on ProgressEvent but with an additional percent property for convenience.
Response
An HTTP response. Content of and meta data about a response to an HTTP request. All meta data (headers, status, statusText) and the response body are available immediately and synchronously.
ResponsePayload
Representation of a response payload. Contains the response instance, the finalized request that initiated the response, and an exception if one occurred.
RetryBackOff
Representation of the back-off method to use when retrying requests. A fixed back-off will space retries out by interval. An exponential back-off will delay retries by d*2^n where d is interval and n is the number of attempts so far.
StreamedHttpBody
Representation of an HTTP request body or an HTTP response body where the body is a stream of bytes. Used for large request or response bodies (often when uploading/downloading a file).
StreamedRequest
Representation of an HTTP request where the request body is sent asynchronously as a stream. The content-type should be set manually.
StreamedResponse
An HTTP response where the entire contents of the response body are not immediately known. Meta data about a response to an HTTP request (headers, status, statusText) are available immediately and synchronously. The response body is available as a stream of bytes.
TransportPlatform
WebSocket
A two-way communication object for WebSocket clients. Establishes a WebSocket connection, sends data or streams of data to the server, and receives data from the server.
WebSocketConnectEvent

Enums

RetryBackOffMethod
The valid retry back-off methods.

Properties

defaultTimeoutThreshold Duration?
Specifies the default timeout for any request without an explicit one.
getter/setter pair
globalTransportPlatform TransportPlatform?
The globally configured transport platform. Any transport class that is not explicitly given a TransportPlatform instance upon construction will inherit this global one.
getter/setter pair

Functions

resetGlobalTransportPlatform() → void
Reset the globally configured transport platform.

Exceptions / Errors

RequestException
An exception that is raised when a response to a request returns with an unsuccessful status code.
ResponseFormatException
An exception that is raised when a response to a request returns with a body that cannot successfully be encoded or decoded based on the expected content-type.
TransportPlatformMissing
WebSocketException
Represents an exception in the connection process of a Web Socket.