0
# HTTP Abstractions
1
2
Core HTTP abstractions providing type-safe representations of HTTP requests, responses, headers, status codes, and media types. These foundational types are used throughout Spring Web for both servlet and reactive web applications.
3
4
## Capabilities
5
6
### HttpEntity and Response Types
7
8
Base classes for representing HTTP request and response entities with headers and body content.
9
10
```java { .api }
11
/**
12
* Represents an HTTP request or response entity consisting of headers and body
13
*/
14
class HttpEntity<T> {
15
/** Create entity with body only */
16
HttpEntity(T body);
17
/** Create entity with headers only */
18
HttpEntity(MultiValueMap<String, String> headers);
19
/** Create entity with both body and headers */
20
HttpEntity(T body, MultiValueMap<String, String> headers);
21
22
/** Get the HTTP headers */
23
HttpHeaders getHeaders();
24
/** Get the body content */
25
T getBody();
26
/** Check if entity has a body */
27
boolean hasBody();
28
}
29
30
/**
31
* Extension of HttpEntity that adds HTTP status code for responses
32
*/
33
class ResponseEntity<T> extends HttpEntity<T> {
34
ResponseEntity(HttpStatusCode status);
35
ResponseEntity(T body, HttpStatusCode status);
36
ResponseEntity(MultiValueMap<String, String> headers, HttpStatusCode status);
37
ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatusCode status);
38
39
/** Get the HTTP status code */
40
HttpStatusCode getStatusCode();
41
42
// Convenience factory methods
43
static <T> ResponseEntity<T> ok(T body);
44
static ResponseEntity<Void> ok();
45
static ResponseEntity.HeadersBuilder<?> noContent();
46
static <T> ResponseEntity<T> badRequest();
47
static <T> ResponseEntity<T> notFound();
48
static ResponseEntity.BodyBuilder status(HttpStatusCode status);
49
}
50
51
/**
52
* Extension of HttpEntity that adds HTTP method and URL for requests
53
*/
54
class RequestEntity<T> extends HttpEntity<T> {
55
RequestEntity(HttpMethod method, URI url);
56
RequestEntity(T body, HttpMethod method, URI url);
57
RequestEntity(MultiValueMap<String, String> headers, HttpMethod method, URI url);
58
RequestEntity(T body, MultiValueMap<String, String> headers, HttpMethod method, URI url);
59
60
/** Get the HTTP method */
61
HttpMethod getMethod();
62
/** Get the request URL */
63
URI getUrl();
64
65
// Convenience factory methods
66
static RequestEntity.HeadersBuilder<?> get(URI url);
67
static RequestEntity.BodyBuilder post(URI url);
68
static RequestEntity.BodyBuilder put(URI url);
69
static RequestEntity.BodyBuilder patch(URI url);
70
static RequestEntity.HeadersBuilder<?> delete(URI url);
71
static RequestEntity.BodyBuilder method(HttpMethod method, URI url);
72
}
73
```
74
75
**Usage Examples:**
76
77
```java
78
// Create response entities
79
ResponseEntity<User> userResponse = ResponseEntity.ok(user);
80
ResponseEntity<Void> noContent = ResponseEntity.noContent().build();
81
ResponseEntity<String> badRequest = ResponseEntity.badRequest().body("Invalid input");
82
83
// Create request entities
84
RequestEntity<User> postRequest = RequestEntity.post(uri)
85
.contentType(MediaType.APPLICATION_JSON)
86
.body(user);
87
88
RequestEntity<Void> getRequest = RequestEntity.get(uri)
89
.header("Authorization", "Bearer token")
90
.build();
91
```
92
93
### HTTP Headers Management
94
95
Comprehensive HTTP headers management with type-safe accessors for common headers.
96
97
```java { .api }
98
/**
99
* HTTP request and response headers as a multi-value map
100
*/
101
class HttpHeaders implements MultiValueMap<String, String> {
102
HttpHeaders();
103
HttpHeaders(MultiValueMap<String, String> otherHeaders);
104
105
// Content negotiation headers
106
void setAccept(List<MediaType> acceptableMediaTypes);
107
List<MediaType> getAccept();
108
void setContentType(MediaType mediaType);
109
MediaType getContentType();
110
111
// Content metadata
112
void setContentLength(long contentLength);
113
long getContentLength();
114
void setContentDisposition(ContentDisposition contentDisposition);
115
ContentDisposition getContentDisposition();
116
117
// Caching headers
118
void setDate(long date);
119
long getDate();
120
void setETag(String etag);
121
String getETag();
122
void setLastModified(long lastModified);
123
long getLastModified();
124
void setCacheControl(CacheControl cacheControl);
125
String getCacheControl();
126
127
// Authentication and authorization
128
void setBearerAuth(String token);
129
void setBasicAuth(String username, String password);
130
void setBasicAuth(String username, String password, Charset charset);
131
132
// CORS headers
133
void setAccessControlAllowCredentials(boolean allowCredentials);
134
void setAccessControlAllowHeaders(List<String> allowedHeaders);
135
void setAccessControlAllowMethods(List<HttpMethod> allowedMethods);
136
void setAccessControlAllowOrigin(String allowedOrigin);
137
void setAccessControlExposeHeaders(List<String> exposedHeaders);
138
void setAccessControlMaxAge(Duration maxAge);
139
140
// Utility methods
141
String getFirst(String headerName);
142
void add(String headerName, String headerValue);
143
void set(String headerName, String headerValue);
144
void setAll(Map<String, String> values);
145
Map<String, String> toSingleValueMap();
146
}
147
```
148
149
**Usage Examples:**
150
151
```java
152
HttpHeaders headers = new HttpHeaders();
153
headers.setContentType(MediaType.APPLICATION_JSON);
154
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML));
155
headers.setBearerAuth("your-jwt-token");
156
headers.add("X-Custom-Header", "custom-value");
157
158
// CORS configuration
159
headers.setAccessControlAllowOrigin("*");
160
headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET, HttpMethod.POST));
161
```
162
163
### HTTP Method Enumeration
164
165
Standardized HTTP method constants with utility methods for method resolution.
166
167
```java { .api }
168
/**
169
* Enumeration of HTTP request methods
170
*/
171
enum HttpMethod {
172
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
173
174
/** Check if method name matches this enum value */
175
boolean matches(String method);
176
177
/** Resolve string method name to HttpMethod enum */
178
static HttpMethod resolve(String method);
179
}
180
```
181
182
### HTTP Status Codes
183
184
Comprehensive HTTP status code enumeration with utility methods for status classification.
185
186
```java { .api }
187
/**
188
* Enumeration of HTTP status codes with utility methods
189
*/
190
enum HttpStatus implements HttpStatusCode {
191
// 1xx Informational
192
CONTINUE(100), SWITCHING_PROTOCOLS(101), PROCESSING(102), EARLY_HINTS(103),
193
194
// 2xx Success
195
OK(200), CREATED(201), ACCEPTED(202), NON_AUTHORITATIVE_INFORMATION(203),
196
NO_CONTENT(204), RESET_CONTENT(205), PARTIAL_CONTENT(206), MULTI_STATUS(207),
197
198
// 3xx Redirection
199
MULTIPLE_CHOICES(300), MOVED_PERMANENTLY(301), FOUND(302), SEE_OTHER(303),
200
NOT_MODIFIED(304), USE_PROXY(305), TEMPORARY_REDIRECT(307), PERMANENT_REDIRECT(308),
201
202
// 4xx Client Error
203
BAD_REQUEST(400), UNAUTHORIZED(401), PAYMENT_REQUIRED(402), FORBIDDEN(403),
204
NOT_FOUND(404), METHOD_NOT_ALLOWED(405), NOT_ACCEPTABLE(406), PROXY_AUTHENTICATION_REQUIRED(407),
205
REQUEST_TIMEOUT(408), CONFLICT(409), GONE(410), LENGTH_REQUIRED(411),
206
207
// 5xx Server Error
208
INTERNAL_SERVER_ERROR(500), NOT_IMPLEMENTED(501), BAD_GATEWAY(502), SERVICE_UNAVAILABLE(503),
209
GATEWAY_TIMEOUT(504), HTTP_VERSION_NOT_SUPPORTED(505);
210
211
/** Get numeric status code value */
212
int value();
213
/** Get standard reason phrase */
214
String getReasonPhrase();
215
/** Get status series (1xx, 2xx, etc.) */
216
HttpStatus.Series series();
217
218
// Status classification methods
219
boolean is1xxInformational();
220
boolean is2xxSuccessful();
221
boolean is3xxRedirection();
222
boolean is4xxClientError();
223
boolean is5xxServerError();
224
boolean isError();
225
226
/** Resolve numeric status code to HttpStatus enum */
227
static HttpStatus valueOf(int statusCode);
228
/** Resolve status code, returning null if not found */
229
static HttpStatus resolve(int statusCode);
230
}
231
232
/**
233
* Series of HTTP status codes
234
*/
235
enum HttpStatus.Series {
236
INFORMATIONAL(1), SUCCESSFUL(2), REDIRECTION(3), CLIENT_ERROR(4), SERVER_ERROR(5);
237
238
int value();
239
static HttpStatus.Series valueOf(int status);
240
static HttpStatus.Series resolve(int statusCode);
241
}
242
```
243
244
### Media Type Support
245
246
Comprehensive media type representation with parsing and compatibility checking.
247
248
```java { .api }
249
/**
250
* Represents an Internet Media Type (MIME type)
251
*/
252
class MediaType extends MimeType {
253
// Common media type constants
254
static final MediaType ALL;
255
static final MediaType APPLICATION_ATOM_XML;
256
static final MediaType APPLICATION_CBOR;
257
static final MediaType APPLICATION_FORM_URLENCODED;
258
static final MediaType APPLICATION_GRAPHQL_RESPONSE;
259
static final MediaType APPLICATION_JSON;
260
static final MediaType APPLICATION_NDJSON;
261
static final MediaType APPLICATION_OCTET_STREAM;
262
static final MediaType APPLICATION_PDF;
263
static final MediaType APPLICATION_PROBLEM_JSON;
264
static final MediaType APPLICATION_PROBLEM_XML;
265
static final MediaType APPLICATION_RSS_XML;
266
static final MediaType APPLICATION_STREAM_JSON;
267
static final MediaType APPLICATION_XHTML_XML;
268
static final MediaType APPLICATION_XML;
269
static final MediaType IMAGE_GIF;
270
static final MediaType IMAGE_JPEG;
271
static final MediaType IMAGE_PNG;
272
static final MediaType MULTIPART_FORM_DATA;
273
static final MediaType MULTIPART_MIXED;
274
static final MediaType MULTIPART_RELATED;
275
static final MediaType TEXT_EVENT_STREAM;
276
static final MediaType TEXT_HTML;
277
static final MediaType TEXT_MARKDOWN;
278
static final MediaType TEXT_PLAIN;
279
static final MediaType TEXT_XML;
280
281
MediaType(String type);
282
MediaType(String type, String subtype);
283
MediaType(String type, String subtype, Charset charset);
284
MediaType(String type, String subtype, double qualityValue);
285
MediaType(String type, String subtype, Map<String, String> parameters);
286
287
/** Get main type (e.g., "text", "application") */
288
String getType();
289
/** Get subtype (e.g., "plain", "json") */
290
String getSubtype();
291
/** Get charset parameter */
292
Charset getCharset();
293
/** Get quality value for content negotiation */
294
double getQualityValue();
295
296
// Compatibility checking
297
boolean includes(MediaType other);
298
boolean isCompatibleWith(MediaType other);
299
boolean isConcrete();
300
boolean isWildcardType();
301
boolean isWildcardSubtype();
302
303
// Factory methods
304
static MediaType parseMediaType(String mediaType);
305
static List<MediaType> parseMediaTypes(String mediaTypes);
306
static List<MediaType> parseMediaTypes(List<String> mediaTypes);
307
static String toString(Collection<MediaType> mediaTypes);
308
309
// Utility methods for sorting
310
static void sortByQualityValue(List<MediaType> mediaTypes);
311
static void sortBySpecificity(List<MediaType> mediaTypes);
312
static void sortBySpecificityAndQuality(List<MediaType> mediaTypes);
313
}
314
```
315
316
**Usage Examples:**
317
318
```java
319
// Create media types
320
MediaType jsonType = MediaType.APPLICATION_JSON;
321
MediaType xmlWithCharset = new MediaType("application", "xml", StandardCharsets.UTF_8);
322
323
// Parse media types
324
MediaType parsed = MediaType.parseMediaType("application/json;charset=UTF-8");
325
List<MediaType> acceptTypes = MediaType.parseMediaTypes("application/json,application/xml;q=0.9");
326
327
// Compatibility checking
328
boolean compatible = MediaType.APPLICATION_JSON.isCompatibleWith(MediaType.APPLICATION_JSON);
329
boolean includes = MediaType.APPLICATION_JSON.includes(MediaType.ALL);
330
```
331
332
### Content Disposition Support
333
334
Support for Content-Disposition header values as defined in RFC 6266.
335
336
```java { .api }
337
/**
338
* Represents Content-Disposition header value
339
*/
340
class ContentDisposition {
341
/** Check if disposition type is "attachment" */
342
boolean isAttachment();
343
/** Check if disposition type is "form-data" */
344
boolean isFormData();
345
/** Check if disposition type is "inline" */
346
boolean isInline();
347
348
/** Get disposition type */
349
String getType();
350
/** Get name parameter (for form-data) */
351
String getName();
352
/** Get filename parameter */
353
String getFilename();
354
/** Get charset for filename */
355
Charset getCharset();
356
/** Get creation date */
357
ZonedDateTime getCreationDate();
358
/** Get modification date */
359
ZonedDateTime getModificationDate();
360
/** Get read date */
361
ZonedDateTime getReadDate();
362
/** Get size parameter */
363
Long getSize();
364
365
// Builder methods
366
static ContentDisposition.Builder attachment();
367
static ContentDisposition.Builder formData();
368
static ContentDisposition.Builder inline();
369
static ContentDisposition parse(String contentDisposition);
370
}
371
372
interface ContentDisposition.Builder {
373
ContentDisposition.Builder name(String name);
374
ContentDisposition.Builder filename(String filename);
375
ContentDisposition.Builder filename(String filename, Charset charset);
376
ContentDisposition.Builder creationDate(ZonedDateTime creationDate);
377
ContentDisposition.Builder modificationDate(ZonedDateTime modificationDate);
378
ContentDisposition.Builder readDate(ZonedDateTime readDate);
379
ContentDisposition.Builder size(Long size);
380
ContentDisposition build();
381
}
382
```
383
384
### Cache Control Support
385
386
Builder for Cache-Control HTTP header values with support for standard directives.
387
388
```java { .api }
389
/**
390
* Builder for Cache-Control HTTP header values
391
*/
392
class CacheControl {
393
// Factory methods
394
static CacheControl empty();
395
static CacheControl maxAge(long maxAge, TimeUnit unit);
396
static CacheControl maxAge(Duration maxAge);
397
static CacheControl noCache();
398
static CacheControl noStore();
399
400
// Directive methods
401
CacheControl mustRevalidate();
402
CacheControl noTransform();
403
CacheControl cachePublic();
404
CacheControl cachePrivate();
405
CacheControl proxyRevalidate();
406
CacheControl sMaxAge(long sMaxAge, TimeUnit unit);
407
CacheControl sMaxAge(Duration sMaxAge);
408
CacheControl staleWhileRevalidate(long staleWhileRevalidate, TimeUnit unit);
409
CacheControl staleWhileRevalidate(Duration staleWhileRevalidate);
410
CacheControl staleIfError(long staleIfError, TimeUnit unit);
411
CacheControl staleIfError(Duration staleIfError);
412
413
/** Get the Cache-Control header value */
414
String getHeaderValue();
415
}
416
```
417
418
**Usage Examples:**
419
420
```java
421
// Cache control configurations
422
CacheControl maxAge = CacheControl.maxAge(1, TimeUnit.HOURS).mustRevalidate();
423
CacheControl noCache = CacheControl.noCache();
424
CacheControl publicCache = CacheControl.maxAge(Duration.ofMinutes(30)).cachePublic();
425
426
// Use in response
427
ResponseEntity<String> response = ResponseEntity.ok()
428
.cacheControl(maxAge)
429
.body("Cached content");
430
```
431
432
### Problem Detail Support
433
434
RFC 7807 Problem Detail for HTTP APIs providing standardized error responses.
435
436
```java { .api }
437
/**
438
* Represents an RFC 7807 Problem Detail for HTTP APIs
439
*/
440
class ProblemDetail {
441
ProblemDetail(int status);
442
443
/** Get problem type URI */
444
URI getType();
445
void setType(URI type);
446
447
/** Get human-readable problem title */
448
String getTitle();
449
void setTitle(String title);
450
451
/** Get HTTP status code */
452
int getStatus();
453
454
/** Get human-readable problem explanation */
455
String getDetail();
456
void setDetail(String detail);
457
458
/** Get problem instance URI */
459
URI getInstance();
460
void setInstance(URI instance);
461
462
/** Get additional properties */
463
Map<String, Object> getProperties();
464
void setProperty(String name, Object value);
465
Object getProperty(String name);
466
467
// Factory methods
468
static ProblemDetail forStatus(HttpStatusCode status);
469
static ProblemDetail forStatus(int status);
470
static ProblemDetail forStatusAndDetail(HttpStatusCode status, String detail);
471
}
472
```
473
474
**Usage Examples:**
475
476
```java
477
// Create problem details
478
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
479
problem.setTitle("Validation Failed");
480
problem.setDetail("The request contains invalid parameters");
481
problem.setProperty("invalidFields", Arrays.asList("email", "age"));
482
483
// Use in exception handler
484
@ExceptionHandler(ValidationException.class)
485
public ResponseEntity<ProblemDetail> handleValidation(ValidationException ex) {
486
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
487
HttpStatus.BAD_REQUEST,
488
ex.getMessage()
489
);
490
return ResponseEntity.badRequest().body(problem);
491
}
492
```
493
494
## Core HTTP Message Interfaces
495
496
Base interfaces for HTTP request and response message abstraction.
497
498
```java { .api }
499
/**
500
* Base interface for HTTP request and response messages
501
*/
502
interface HttpMessage {
503
/** Get the HTTP headers */
504
HttpHeaders getHeaders();
505
}
506
507
/**
508
* HTTP input message with readable body content
509
*/
510
interface HttpInputMessage extends HttpMessage {
511
/** Get the message body as an input stream */
512
InputStream getBody() throws IOException;
513
}
514
515
/**
516
* HTTP output message with writable body content
517
*/
518
interface HttpOutputMessage extends HttpMessage {
519
/** Get the message body as an output stream */
520
OutputStream getBody() throws IOException;
521
}
522
523
/**
524
* HTTP request message
525
*/
526
interface HttpRequest extends HttpMessage {
527
/** Get the HTTP method */
528
HttpMethod getMethod();
529
/** Get the request URI */
530
URI getURI();
531
}
532
533
/**
534
* Reactive HTTP input message with streaming body
535
*/
536
interface ReactiveHttpInputMessage extends HttpMessage {
537
/** Get the message body as a reactive stream */
538
Flux<DataBuffer> getBody();
539
}
540
541
/**
542
* Reactive HTTP output message with streaming body
543
*/
544
interface ReactiveHttpOutputMessage extends HttpMessage {
545
/** Get the data buffer factory */
546
DataBufferFactory bufferFactory();
547
/** Register action to execute before commit */
548
void beforeCommit(Supplier<? extends Mono<Void>> action);
549
/** Check if response is committed */
550
boolean isCommitted();
551
/** Write body content */
552
Mono<Void> writeWith(Publisher<? extends DataBuffer> body);
553
/** Write and flush body content */
554
Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body);
555
/** Complete the response */
556
Mono<Void> setComplete();
557
}
558
```