
# HTTP transport

An `HttpTransport` sends one `HttpRequest` and returns an `HttpResponse` with the status, the headers and the body bytes. It is the layer under the Feign clients and the OAuth2 token clients, and you can replace it: a mock in tests, or your own on top of Dio or `package:http`.

## Why

Dart has two HTTP stacks: `dart:io`'s `HttpClient` and the browser's `fetch`. Code that must run on a server, in a Flutter app and on the web needs one interface over both, with the same timeouts and errors. `platformHttpTransport()` picks the right one.

## Example

```dart
final transport = platformHttpTransport(connectTimeout: const Duration(seconds: 3));
final response = await transport.send(
  HttpRequest(
    method: HttpMethod.post,
    url: Uri.parse('https://api.neon.books/books'),
    headers: HttpHeaders({HttpHeaders.contentTypeHeader: MediaType.applicationJson}),
    body: utf8.encode('{"isbn":"1"}'),
    readTimeout: const Duration(seconds: 60), // a slow report: wait longer for data
  ),
);
if (response.statusCode.is2xxSuccessful) log.info(response.bodyText);
transport.close();
```

## Transports

| Transport | Platforms | Import |
|---|---|---|
| `platformHttpTransport()` | picks one of the two below | `package:spring_web_dart/spring_web_dart.dart` |
| `IoHttpTransport` | VM, Flutter on Android, iOS and desktop (`dart:io` `HttpClient`) | `package:spring_web_dart/io.dart` |
| `FetchHttpTransport` | web, Flutter web (`fetch` through `dart:js_interop`) | `package:spring_web_dart/browser.dart` |
| `MockHttpTransport` | tests | `package:spring_web_dart/testing.dart`, or `spring_boot_starter_test` |
| your own | e.g. on Dio or `package:http` | implement `HttpTransport` (`send`, `stream`, `close`) |

## HttpRequest

| Field | Meaning |
|---|---|
| `method`, `url` | Required. |
| `headers` | An `HttpHeaders`; an empty, writable set by default. |
| `body` | The bytes. |
| `readTimeout` | The longest wait for data: first for the response, then between two chunks of the body. The read timeout of Spring and Feign. |
| `timeout` | A deadline for the whole exchange, which Spring's request factories do not have. |
| `followRedirects` | `true` by default; with `false`, a `3xx` response is returned instead of followed. |

Both timeouts are `null` (no limit) by default. When either runs out, the request is aborted with an `HttpTransportException` whose `isTimeout` is `true`.

## Responses and errors

- Every status code is a normal response, a 404 or a 500 included: check `response.statusCode`.
- Only network failures and timeouts throw an `HttpTransportException` (`isTimeout` tells which).
- `HttpResponse` has `statusCode` (an `HttpStatusCode`), `headers`, `body` (bytes), `bodyText` (decoded with the `charset` of the content type, else UTF-8) and the `request`.

## platformHttpTransport options

| Option | Default | Meaning |
|---|---|---|
| `connectTimeout` | none | How long opening a connection may take; ignored in the browser (`fetch` has no such setting). |
| `credentials` | `FetchCredentials.sameOrigin` | Browser only: whether `fetch` sends cookies to the server. |
| `allowBadCertificates` | `false` | `dart:io` only: accept an expired, self-signed or foreign certificate. For the configuration downloads of `spring.remote.allow-insecure` only; never for an API. |

On a platform with neither `dart:io` nor `dart:js_interop` it throws an `UnsupportedError`: pass your own transport there.

## Platform behaviour

- `IoHttpTransport` follows redirects as far as `HttpClient` does (`GET` and `HEAD`, and `303` after a `POST`), and aborts the request when a timeout runs out. `connectTimeout` bounds each connection.
- `FetchHttpTransport` follows redirects (`followRedirects: false` gives the browser's opaque redirect, status 0) and aborts through an `AbortController`. The server must allow the request with CORS headers; a blocked request is an `HttpTransportException`.

## Streaming responses

For a large download or an endless response, `transport.stream(request)` returns as soon as the status and the headers arrive, and the body comes as byte chunks (`StreamedHttpResponse.body`). The request's `timeout` and `readTimeout` cover only the wait for the headers. Cancelling the subscription closes the connection.

```dart
final response = await transport.stream(request);
// An error answer is short: read it whole for the message.
if (!response.isSuccess) throw StateError((await response.read()).bodyText);
await for (final chunk in response.body) {
  sink.add(chunk);
}
```

## In an application

The Feign starter sends through the `HttpTransport` bean (`platformHttpTransport()` unless you declare one), and its `connect-timeout` configures the default one. Declare an `HttpTransport` bean to replace it for every client; `BeanOverride<HttpTransport>(MockHttpTransport())` does so in tests.

## In Spring (Java)

```java
RestClient client = RestClient.builder().requestFactory(new JdkClientHttpRequestFactory()).build();
```

`HttpTransport` plays the part of Spring's `ClientHttpRequestFactory` / `ClientHttpRequest`, at a lower level than `RestClient`. The `timeout` deadline is an addition.

## See also

- [Server-sent events](server-sent-events.md)
- [Testing](testing.md)
- [spring_boot_starter_feign](../spring-boot-starter-feign/index.md)
