0
# HTTP/1.1 Protocol Implementation
1
2
Complete HTTP/1.1 protocol implementation with connection management, request parsing, response generation, and upgrade capabilities for handling HTTP/1.1 communications.
3
4
## Capabilities
5
6
### Http1Config Interface
7
8
Configuration interface for HTTP/1.1 protocol settings and behavior.
9
10
```java { .api }
11
/**
12
* Configuration for HTTP/1.1 protocol.
13
*/
14
interface Http1Config extends Prototype.Api {
15
/**
16
* Create builder for HTTP/1.1 configuration.
17
* @return configuration builder
18
*/
19
static Builder builder();
20
21
/**
22
* Get maximum header size allowed.
23
* @return maximum header size in bytes
24
*/
25
int maxHeaderSize();
26
27
/**
28
* Get maximum initial line length.
29
* @return maximum initial line length
30
*/
31
int maxInitialLineLength();
32
33
/**
34
* Get maximum chunk size for chunked encoding.
35
* @return maximum chunk size
36
*/
37
int maxChunkSize();
38
39
/**
40
* Check if request validation is enabled.
41
* @return true if request validation enabled
42
*/
43
boolean validateRequestHeaders();
44
45
/**
46
* Check if host header validation is enabled.
47
* @return true if host header validation enabled
48
*/
49
boolean validateHostHeader();
50
51
/**
52
* Check if continue processing is enabled for Expect: 100-continue.
53
* @return true if continue processing enabled
54
*/
55
boolean continueImmediately();
56
57
/**
58
* Get connection idle timeout.
59
* @return idle timeout duration
60
*/
61
Duration connectionIdleTimeout();
62
63
/**
64
* Check if pipelining is enabled.
65
* @return true if HTTP/1.1 pipelining enabled
66
*/
67
boolean enablePipelining();
68
69
/**
70
* Get maximum number of pipelined requests.
71
* @return maximum pipelined requests
72
*/
73
int maxPipelinedRequests();
74
}
75
```
76
77
**Usage Examples:**
78
79
```java
80
import io.helidon.webserver.http1.Http1Config;
81
import java.time.Duration;
82
83
// Basic HTTP/1.1 configuration
84
Http1Config basicConfig = Http1Config.builder()
85
.maxHeaderSize(8192)
86
.maxInitialLineLength(4096)
87
.validateRequestHeaders(true)
88
.build();
89
90
// High-performance HTTP/1.1 configuration
91
Http1Config highPerfConfig = Http1Config.builder()
92
.maxHeaderSize(16384)
93
.maxInitialLineLength(8192)
94
.maxChunkSize(65536)
95
.validateRequestHeaders(true)
96
.validateHostHeader(true)
97
.continueImmediately(true)
98
.connectionIdleTimeout(Duration.ofMinutes(5))
99
.enablePipelining(true)
100
.maxPipelinedRequests(100)
101
.build();
102
103
// Use in server configuration
104
WebServerConfig serverConfig = WebServerConfig.builder()
105
.port(8080)
106
.addProtocol(highPerfConfig)
107
.routing(HttpRouting.builder()
108
.get("/", (req, res) -> res.send("Hello HTTP/1.1"))
109
.build())
110
.build();
111
```
112
113
### Http1Connection Class
114
115
HTTP/1.1 connection implementation handling individual client connections.
116
117
```java { .api }
118
/**
119
* HTTP/1.1 connection implementation.
120
*/
121
class Http1Connection implements ServerConnection {
122
/**
123
* Get connection channel.
124
* @return connection channel
125
*/
126
SocketChannel channel();
127
128
/**
129
* Get connection context.
130
* @return connection context
131
*/
132
ConnectionContext context();
133
134
/**
135
* Check if connection is secure (TLS).
136
* @return true if secure connection
137
*/
138
boolean isSecure();
139
140
/**
141
* Get local address.
142
* @return local socket address
143
*/
144
SocketAddress localAddress();
145
146
/**
147
* Get remote address.
148
* @return remote socket address
149
*/
150
SocketAddress remoteAddress();
151
152
/**
153
* Close the connection.
154
*/
155
void close();
156
157
/**
158
* Check if connection is still active.
159
* @return true if connection active
160
*/
161
boolean isActive();
162
163
/**
164
* Handle connection lifecycle.
165
*/
166
void handle();
167
}
168
```
169
170
### Http1ServerRequest Class
171
172
HTTP/1.1 server request implementation for processing incoming requests.
173
174
```java { .api }
175
/**
176
* HTTP/1.1 server request implementation.
177
*/
178
class Http1ServerRequest implements ServerRequest {
179
/**
180
* Get HTTP method.
181
* @return HTTP method
182
*/
183
Method method();
184
185
/**
186
* Get request URI.
187
* @return request URI
188
*/
189
UriInfo requestedUri();
190
191
/**
192
* Get request headers.
193
* @return HTTP/1.1 headers
194
*/
195
Http1Headers headers();
196
197
/**
198
* Get request entity.
199
* @return request entity
200
*/
201
ServerRequestEntity entity();
202
203
/**
204
* Get path information.
205
* @return server request path
206
*/
207
ServerRequestPath path();
208
209
/**
210
* Get query parameters.
211
* @return query parameters
212
*/
213
Parameters query();
214
215
/**
216
* Get HTTP version.
217
* @return HTTP version (1.1)
218
*/
219
Version version();
220
221
/**
222
* Get connection information.
223
* @return connection details
224
*/
225
ConnectionInfo connectionInfo();
226
227
/**
228
* Get request context.
229
* @return request context
230
*/
231
Context context();
232
}
233
```
234
235
### Http1ServerResponse Class
236
237
HTTP/1.1 server response implementation for generating responses.
238
239
```java { .api }
240
/**
241
* HTTP/1.1 server response implementation.
242
*/
243
class Http1ServerResponse implements ServerResponse {
244
/**
245
* Set response status.
246
* @param status HTTP status
247
* @return this response for chaining
248
*/
249
Http1ServerResponse status(Status status);
250
251
/**
252
* Set response headers.
253
* @param headers response headers
254
* @return this response for chaining
255
*/
256
Http1ServerResponse headers(WritableHeaders<?> headers);
257
258
/**
259
* Add response header.
260
* @param name header name
261
* @param value header value
262
* @return this response for chaining
263
*/
264
Http1ServerResponse header(String name, String value);
265
266
/**
267
* Set content type.
268
* @param contentType media type
269
* @return this response for chaining
270
*/
271
Http1ServerResponse contentType(MediaType contentType);
272
273
/**
274
* Send response with content.
275
* @param entity response content
276
*/
277
void send(String entity);
278
279
/**
280
* Send response with binary content.
281
* @param entity binary content
282
*/
283
void send(byte[] entity);
284
285
/**
286
* Send response with stream content.
287
* @param entity input stream
288
*/
289
void send(InputStream entity);
290
291
/**
292
* Send empty response.
293
*/
294
void send();
295
296
/**
297
* Get output stream for streaming responses.
298
* @return output stream
299
*/
300
OutputStream outputStream();
301
302
/**
303
* Check if headers have been sent.
304
* @return true if headers sent
305
*/
306
boolean headersSent();
307
308
/**
309
* Close the response.
310
*/
311
void close();
312
}
313
```
314
315
### Http1Headers Class
316
317
HTTP/1.1 headers implementation with case-insensitive header handling.
318
319
```java { .api }
320
/**
321
* HTTP/1.1 headers implementation.
322
*/
323
class Http1Headers implements ServerRequestHeaders {
324
/**
325
* Get header value.
326
* @param name header name (case-insensitive)
327
* @return optional header value
328
*/
329
Optional<String> first(String name);
330
331
/**
332
* Get all header values.
333
* @param name header name (case-insensitive)
334
* @return list of header values
335
*/
336
List<String> all(String name);
337
338
/**
339
* Check if header exists.
340
* @param name header name (case-insensitive)
341
* @return true if header exists
342
*/
343
boolean contains(String name);
344
345
/**
346
* Get all header names.
347
* @return set of header names
348
*/
349
Set<String> names();
350
351
/**
352
* Get content type header.
353
* @return optional media type
354
*/
355
Optional<MediaType> contentType();
356
357
/**
358
* Get content length header.
359
* @return optional content length
360
*/
361
OptionalLong contentLength();
362
363
/**
364
* Get accept header values.
365
* @return list of accepted media types
366
*/
367
List<MediaType> acceptedTypes();
368
369
/**
370
* Convert to map.
371
* @return map of headers
372
*/
373
Map<String, List<String>> toMap();
374
}
375
```
376
377
**Usage Examples:**
378
379
```java
380
// Custom HTTP/1.1 request handler
381
Handler http1Handler = (req, res) -> {
382
if (req instanceof Http1ServerRequest http1Request) {
383
// Access HTTP/1.1 specific features
384
Http1Headers headers = http1Request.headers();
385
Version version = http1Request.version(); // Will be HTTP/1.1
386
387
// Check specific HTTP/1.1 headers
388
Optional<String> connection = headers.first("Connection");
389
Optional<String> transferEncoding = headers.first("Transfer-Encoding");
390
boolean keepAlive = connection.map(c -> c.toLowerCase().contains("keep-alive"))
391
.orElse(false);
392
393
String response = String.format(
394
"HTTP Version: %s, Keep-Alive: %s",
395
version, keepAlive
396
);
397
398
if (res instanceof Http1ServerResponse http1Response) {
399
// HTTP/1.1 specific response handling
400
if (keepAlive) {
401
http1Response.header("Connection", "keep-alive");
402
}
403
http1Response.send(response);
404
}
405
}
406
};
407
```
408
409
### Http1Prologue Class
410
411
HTTP/1.1 request prologue (request line) parsing and handling.
412
413
```java { .api }
414
/**
415
* HTTP/1.1 request prologue (request line).
416
*/
417
class Http1Prologue {
418
/**
419
* Get HTTP method from prologue.
420
* @return HTTP method
421
*/
422
Method method();
423
424
/**
425
* Get request URI from prologue.
426
* @return request URI
427
*/
428
UriInfo uri();
429
430
/**
431
* Get HTTP version from prologue.
432
* @return HTTP version
433
*/
434
Version version();
435
436
/**
437
* Get raw request line.
438
* @return raw request line string
439
*/
440
String rawRequestLine();
441
442
/**
443
* Parse prologue from request line.
444
* @param requestLine raw request line
445
* @return parsed prologue
446
*/
447
static Http1Prologue parse(String requestLine);
448
449
/**
450
* Validate prologue format.
451
* @return true if prologue is valid
452
*/
453
boolean isValid();
454
}
455
```
456
457
### Connection Management Components
458
459
Components for managing HTTP/1.1 connections and lifecycle.
460
461
```java { .api }
462
/**
463
* HTTP/1.1 connection selector for choosing connections.
464
*/
465
class Http1ConnectionSelector implements ServerConnectionSelector {
466
/**
467
* Select connection for request.
468
* @param context connection context
469
* @return selected connection
470
*/
471
ServerConnection select(ConnectionContext context);
472
473
/**
474
* Release connection after use.
475
* @param connection connection to release
476
*/
477
void release(ServerConnection connection);
478
}
479
480
/**
481
* HTTP/1.1 connection provider for creating connections.
482
*/
483
class Http1ConnectionProvider implements ServerConnectionSelectorProvider {
484
/**
485
* Create connection selector.
486
* @param config connection selector configuration
487
* @return connection selector
488
*/
489
ServerConnectionSelector create(Http1ConnectionSelectorConfig config);
490
491
/**
492
* Get provider name.
493
* @return provider name
494
*/
495
String name();
496
497
/**
498
* Get configuration type.
499
* @return configuration class
500
*/
501
Class<? extends ProtocolConfig> configType();
502
}
503
504
/**
505
* HTTP/1.1 connection listener for connection events.
506
*/
507
interface Http1ConnectionListener {
508
/**
509
* Called when connection is established.
510
* @param connection the established connection
511
*/
512
void connectionOpened(Http1Connection connection);
513
514
/**
515
* Called when connection is closed.
516
* @param connection the closed connection
517
*/
518
void connectionClosed(Http1Connection connection);
519
520
/**
521
* Called when request is received.
522
* @param connection the connection
523
* @param request the received request
524
*/
525
void requestReceived(Http1Connection connection, Http1ServerRequest request);
526
527
/**
528
* Called when response is sent.
529
* @param connection the connection
530
* @param response the sent response
531
*/
532
void responseSent(Http1Connection connection, Http1ServerResponse response);
533
}
534
```
535
536
### Protocol Configuration
537
538
Configuration components for HTTP/1.1 protocol setup.
539
540
```java { .api }
541
/**
542
* HTTP/1.1 protocol configuration provider.
543
*/
544
class Http1ProtocolConfigProvider implements ProtocolConfigProvider {
545
/**
546
* Get configuration type supported by this provider.
547
* @return HTTP/1.1 configuration class
548
*/
549
Class<Http1Config> configType();
550
551
/**
552
* Create protocol configuration.
553
* @param config configuration source
554
* @return protocol configuration
555
*/
556
ProtocolConfig create(Config config);
557
558
/**
559
* Get provider name.
560
* @return provider name ("http_1_1")
561
*/
562
String protocolType();
563
}
564
```
565
566
## Advanced HTTP/1.1 Features
567
568
### Connection Keep-Alive Handling
569
570
```java
571
Http1Config keepAliveConfig = Http1Config.builder()
572
.connectionIdleTimeout(Duration.ofMinutes(5))
573
.enablePipelining(false) // Disable for better compatibility
574
.continueImmediately(true)
575
.build();
576
577
// Handler that works with keep-alive connections
578
Handler keepAliveHandler = (req, res) -> {
579
Http1Headers headers = ((Http1ServerRequest) req).headers();
580
Optional<String> connection = headers.first("Connection");
581
582
boolean keepAlive = connection
583
.map(c -> c.toLowerCase().contains("keep-alive"))
584
.orElse(req.version().equals(Version.V1_1)); // Default for HTTP/1.1
585
586
if (keepAlive) {
587
res.header("Connection", "keep-alive")
588
.header("Keep-Alive", "timeout=300, max=100");
589
} else {
590
res.header("Connection", "close");
591
}
592
593
res.send("Response with keep-alive handling");
594
};
595
```
596
597
### Chunked Transfer Encoding
598
599
```java
600
// Handler for chunked responses
601
Handler chunkedHandler = (req, res) -> {
602
Http1ServerResponse http1Response = (Http1ServerResponse) res;
603
604
http1Response.status(200)
605
.contentType(MediaType.TEXT_PLAIN)
606
.header("Transfer-Encoding", "chunked");
607
608
try (OutputStream out = http1Response.outputStream()) {
609
for (int i = 0; i < 10; i++) {
610
String chunk = "Chunk " + i + "\n";
611
out.write(chunk.getBytes());
612
out.flush();
613
Thread.sleep(100); // Simulate processing
614
}
615
} catch (Exception e) {
616
// Handle streaming error
617
}
618
};
619
620
// Configure chunked encoding limits
621
Http1Config chunkedConfig = Http1Config.builder()
622
.maxChunkSize(65536) // 64KB chunks
623
.validateRequestHeaders(true)
624
.build();
625
```
626
627
### Request Validation and Security
628
629
```java
630
// Strict HTTP/1.1 validation configuration
631
Http1Config strictConfig = Http1Config.builder()
632
.validateRequestHeaders(true)
633
.validateHostHeader(true)
634
.maxHeaderSize(8192)
635
.maxInitialLineLength(4096)
636
.build();
637
638
// Custom validation handler
639
Handler validationHandler = (req, res) -> {
640
Http1ServerRequest http1Req = (Http1ServerRequest) req;
641
Http1Headers headers = http1Req.headers();
642
643
// Validate required headers for HTTP/1.1
644
if (req.version().equals(Version.V1_1) && !headers.contains("Host")) {
645
res.status(400).send("Host header required for HTTP/1.1");
646
return;
647
}
648
649
// Validate content length for POST/PUT requests
650
if ((req.method().equals(Method.POST) || req.method().equals(Method.PUT))) {
651
if (!headers.contentLength().isPresent() &&
652
!headers.first("Transfer-Encoding").map(te -> te.contains("chunked")).orElse(false)) {
653
res.status(400).send("Content-Length or Transfer-Encoding required");
654
return;
655
}
656
}
657
658
// Validate content type for requests with body
659
if (req.entity().hasEntity() && !headers.contentType().isPresent()) {
660
res.status(400).send("Content-Type header required");
661
return;
662
}
663
664
res.send("Request validated successfully");
665
};
666
```
667
668
### HTTP/1.1 Upgrade Handling
669
670
```java
671
// HTTP/1.1 upgrade support is handled through SPI
672
// See http1-spi.md for upgrade provider implementation
673
674
// Example usage in routing
675
Handler upgradeHandler = (req, res) -> {
676
Http1Headers headers = ((Http1ServerRequest) req).headers();
677
Optional<String> upgrade = headers.first("Upgrade");
678
Optional<String> connection = headers.first("Connection");
679
680
if (upgrade.isPresent() &&
681
connection.map(c -> c.toLowerCase().contains("upgrade")).orElse(false)) {
682
683
String upgradeProtocol = upgrade.get().toLowerCase();
684
685
if ("websocket".equals(upgradeProtocol)) {
686
// WebSocket upgrade would be handled by WebSocket upgrade provider
687
res.status(101)
688
.header("Upgrade", "websocket")
689
.header("Connection", "Upgrade")
690
.send();
691
} else {
692
res.status(400).send("Unsupported upgrade protocol: " + upgradeProtocol);
693
}
694
} else {
695
res.status(400).send("Invalid upgrade request");
696
}
697
};
698
```
699
700
### Performance Optimization
701
702
```java
703
// High-performance HTTP/1.1 configuration
704
Http1Config performanceConfig = Http1Config.builder()
705
// Increase buffer sizes for high-throughput scenarios
706
.maxHeaderSize(32768)
707
.maxInitialLineLength(16384)
708
.maxChunkSize(131072) // 128KB chunks
709
710
// Enable pipelining for clients that support it
711
.enablePipelining(true)
712
.maxPipelinedRequests(50)
713
714
// Optimize timeouts
715
.connectionIdleTimeout(Duration.ofMinutes(2))
716
.continueImmediately(true)
717
718
// Enable validation for security
719
.validateRequestHeaders(true)
720
.validateHostHeader(true)
721
722
.build();
723
724
// Use with optimized connection configuration
725
ConnectionConfig connConfig = ConnectionConfig.builder()
726
.connectTimeout(Duration.ofSeconds(5))
727
.readTimeout(Duration.ofSeconds(30))
728
.idleTimeout(Duration.ofMinutes(2))
729
.maxConcurrentRequests(1000)
730
.initialBufferSize(32768)
731
.maxBufferSize(1048576)
732
.connectionPooling(true)
733
.build();
734
735
WebServerConfig optimizedServer = WebServerConfig.builder()
736
.port(8080)
737
.connection(connConfig)
738
.addProtocol(performanceConfig)
739
.routing(httpRouting)
740
.build();
741
```