HTTP の型
サーバー、クライアント、テストが共有する、リクエストとレスポンスの構成要素です。ステータスとヘッダーを持つレスポンス (ResponseEntity)、ヘッダー (HttpHeaders)、ステータスコード (HttpStatus)、メディアタイプ (MediaType)、標準のエラーボディ (ProblemDetail)、そしてマルチパートのファイルです。
使う理由
コントローラーも、Feign クライアントも、テストも、同じものについて話します。404、Content-Type、JSON のエラーボディです。Spring の名前を持つ一つの型の集まりにすることで、それらは交換可能で、なじみやすいものになります。
例
// トークンを求める API への呼び出しのヘッダー。
final headers = HttpHeaders()
..contentType = MediaType.applicationJson
..setBearerAuth(token);
headers.forEach((name, values) => log.debug('$name: ${values.join(', ')}'));
// ステータスコードは int なので、直接比較できる。
if (response.statusCode.is2xxSuccessful) { /* ... */ }
if (response.statusCode == HttpStatus.notFound) { /* ... */ }
HttpStatus.valueOf(503).reasonPhrase; // 'Service Unavailable'
// ステータスと Location ヘッダーを持つコントローラーの応答。
ResponseEntity<Book> created(Book book) =>
ResponseEntity.created(Uri.parse('/api/books/${book.isbn}')).body(book);
// 存在しない本へのリクエストに対する応答。
final problem = ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No book 978-0')
..setProperty('isbn', '978-0'); // クライアントがどの本かを表示できる
problem.toJson();
// {type: about:blank, title: Not Found, status: 404, detail: No book 978-0, isbn: 978-0}
レスポンス、ヘッダー、ステータス
| 型 | Spring | 内容 |
|---|---|---|
ResponseEntity<T> |
ResponseEntity<T> |
ステータスコード、ヘッダー、ボディ。ResponseEntity.ok(body)、ResponseEntity.created(uri).body(x)、ResponseEntity.notFound().build()、ResponseEntity.status(s)、accepted()、noContent()、badRequest()、unprocessableContent()、internalServerError()、ResponseEntity.of(nullableBody) (または ofNullable)。 |
HttpHeaders |
HttpHeaders |
名前ごとのヘッダー。大文字小文字を区別せず、名前ごとに複数の値を持ち、順序と大文字小文字の表記を保つ。forEach((name, values))、toSingleValueMap()、toMap()、getAll、operator [] (最初の値)。型付きのアクセサー contentType、accept、eTag、ifNoneMatch、lastModified、date、contentDisposition、location、contentLength。setBearerAuth、setBasicAuth。HttpHeaders.contentTypeHeader のような定数。 |
HttpStatus |
HttpStatus |
Spring 7 のすべてのステータスを int の定数として (notFound、unprocessableContent、contentTooLarge...)。reasonPhrase、series、is2xxSuccessful、is4xxClientError、isError。valueOf(404)、resolve(599)。100 Continue は HttpStatus.continue_。 |
HttpStatusCode |
HttpStatusCode |
任意のステータスコード。定数のないものも: HttpStatusCode.valueOf(599).is5xxServerError。レスポンスの statusCode はこの型。 |
HttpStatusSeries |
HttpStatus.Series |
informational、successful、redirection、clientError、serverError。 |
HttpMethod |
HttpMethod |
get、post...。value はテキスト (GET)、parse('POST') はそれを読む (大文字小文字を区別する。それ以外のテキストは例外を投げる)。 |
MediaType |
MediaType |
文字列としての定数 (applicationJson、applicationProblemJson...)。アノテーションで使える。MediaType.parse は includes、isCompatibleWith、charset、qualityValue を持つオブジェクトを返す。 |
CacheControl |
CacheControl |
Cache-Control の値: CacheControl.maxAge(d)、.noCache()、.noStore()、.empty()、その後に追加のディレクティブ。 |
エラー: ProblemDetail
API のエラーには、クライアントが読めるボディが必要です。ProblemDetail はその標準 (RFC 9457、application/problem+json) で、ステータス、短いタイトル、詳細のテキスト、任意の追加フィールドを持ちます。
| 型 | Spring | 内容 |
|---|---|---|
ProblemDetail |
ProblemDetail |
type (デフォルトは about:blank)、title (デフォルトはステータスのリーズンフレーズ)、status、detail、instance、追加の properties。forStatus、forStatusAndDetail、setProperty、toJson、fromJson。 |
ErrorResponse |
ErrorResponse |
自分の応答を知っている例外: statusCode、headers、body (ProblemDetail)。 |
ErrorResponseException |
同じ | 投げたり継承したりするための ErrorResponse: ErrorResponseException(status, body:, headers:, cause:)。 |
ResponseStatusException |
同じ | ステータスで失敗する最も短い方法: throw ResponseStatusException(HttpStatus.notFound, 'No book 9')。 |
Web サーバーは、自分のエラーに ProblemDetail を書きます (Web スターターの ProblemDetail を参照)。
マルチパートとファイル
アップロードは multipart/form-data として運ばれます。パートからなる一つのボディで、各パートはフォームのフィールドかファイルです。
| 型 | Spring | 内容 |
|---|---|---|
MultipartFile |
MultipartFile |
アップロードされたファイル: name、originalFilename、contentType、size、isEmpty、headers、bytes、openRead()、transferTo(path)。 |
InMemoryMultipartFile |
MockMultipartFile (おおよそ) |
メモリ上に保持される MultipartFile。クライアントが送るファイルなど (InMemoryMultipartFile.fromString(name, text))。 |
MultipartParser |
StandardServletMultipartResolver の解析 |
multipart/* のボディを、届くそばからパートごとに読む: MultipartParser.boundaryOf(contentType)、bind(body)。 |
MultipartBody、MultipartBodyPart |
MultipartBodyBuilder |
MultipartBodyPart.field、.file、.json のパートからボディを書く。contentType (境界付き)、encode()。 |
MediaTypeFactory |
MediaTypeFactory |
ファイル名のメディアタイプ: MediaTypeFactory.getMediaType('cover.png') は image/png。不明なら null。 |
// 素のトランスポートで、本をその表紙とともにアップロードする。
final body = MultipartBody([
MultipartBodyPart.field('title', 'Dune'),
MultipartBodyPart.file('cover', bytes, filename: 'dune.png'), // 名前から image/png
]);
await transport.send(HttpRequest(
method: HttpMethod.post,
url: Uri.parse('https://api.neon.books/books'),
headers: HttpHeaders({HttpHeaders.contentTypeHeader: body.contentType}),
body: body.encode(),
));
Spring (Java) との対応
名前は Spring のもので、形は Dart のものです。HttpStatus の定数は int で (name() はない)、HttpHeaders の定数は Header で終わり (単なる名前は型付きのアクセサーです)、MediaType の定数は文字列で、ResponseEntity.of は nullable なボディを受け取ります。すべての違いは Spring との違い にあります。