0
# HTTP Parsing and Generation
1
2
High-performance HTTP message parsing and generation with configurable compliance modes, efficient buffer management, and support for both request and response processing.
3
4
## Capabilities
5
6
### HttpParser Class
7
8
High-performance HTTP message parser with compliance validation and handler-based processing.
9
10
```java { .api }
11
/**
12
* HTTP message parser with compliance validation
13
*/
14
class HttpParser {
15
/** Create parser for HTTP requests */
16
HttpParser(RequestHandler requestHandler);
17
18
/** Create parser for HTTP responses */
19
HttpParser(ResponseHandler responseHandler);
20
21
/** Create request parser with header size limit */
22
HttpParser(RequestHandler requestHandler, int maxHeaderSize);
23
24
/** Create response parser with compliance mode */
25
HttpParser(ResponseHandler responseHandler, HttpCompliance compliance);
26
27
/** Create parser with full configuration */
28
HttpParser(RequestHandler requestHandler, int maxHeaderSize,
29
HttpCompliance compliance);
30
31
/** Parse next chunk of data from buffer */
32
boolean parseNext(ByteBuffer buffer);
33
34
/** Reset parser to initial state */
35
void reset();
36
37
/** Close parser and release resources */
38
void close();
39
40
/** Check if parser is at start state */
41
boolean isStart();
42
43
/** Check if parsing is complete */
44
boolean isComplete();
45
46
/** Check if parser is closed */
47
boolean isClosed();
48
49
/** Get number of content bytes parsed */
50
int getLength();
51
52
/** Get expected content length from headers */
53
long getContentLength();
54
55
/** Check if using chunked transfer encoding */
56
boolean isChunking();
57
58
/** Get current HTTP compliance mode */
59
HttpCompliance getHttpCompliance();
60
61
/** Get compliance violation listener */
62
ComplianceViolation.Listener getComplianceViolationListener();
63
64
/** Set compliance violation listener */
65
void setComplianceViolationListener(ComplianceViolation.Listener listener);
66
67
/**
68
* Handler interface for HTTP requests
69
*/
70
interface RequestHandler extends HttpHandler {
71
/** Handle parsed request line */
72
boolean startRequest(String method, String uri, HttpVersion version);
73
74
/** Handle request content */
75
boolean content(ByteBuffer item);
76
77
/** Handle request trailers */
78
boolean trailers(HttpFields trailers);
79
80
/** Handle early EOF during request */
81
void earlyEOF();
82
}
83
84
/**
85
* Handler interface for HTTP responses
86
*/
87
interface ResponseHandler extends HttpHandler {
88
/** Handle parsed response status line */
89
boolean startResponse(HttpVersion version, int status, String reason);
90
91
/** Handle response content */
92
boolean content(ByteBuffer item);
93
94
/** Handle response trailers */
95
boolean trailers(HttpFields trailers);
96
97
/** Handle early EOF during response */
98
void earlyEOF();
99
}
100
101
/**
102
* Common handler interface
103
*/
104
interface HttpHandler {
105
/** Handle parsed header */
106
boolean header(HttpField field);
107
108
/** Handle end of headers */
109
boolean headerComplete();
110
111
/** Handle end of message */
112
boolean messageComplete();
113
114
/** Handle parsing errors */
115
void badMessage(BadMessageException failure);
116
117
/** Get header cache index for field names */
118
default int getHeaderCacheSize() { return 1024; }
119
}
120
}
121
```
122
123
### HttpGenerator Class
124
125
HTTP response and request generation with efficient buffer management.
126
127
```java { .api }
128
/**
129
* HTTP message generator with buffer management
130
*/
131
class HttpGenerator {
132
/** Create generator with default settings */
133
HttpGenerator();
134
135
/** Create generator with server version and powered-by options */
136
HttpGenerator(boolean sendServerVersion, boolean sendXPoweredBy);
137
138
/** Generate HTTP request */
139
Result generateRequest(MetaData.Request info, ByteBuffer header,
140
ByteBuffer chunk, ByteBuffer content, boolean last);
141
142
/** Generate HTTP response */
143
Result generateResponse(MetaData.Response info, boolean head,
144
ByteBuffer header, ByteBuffer chunk,
145
ByteBuffer content, boolean last);
146
147
/** Check if generation is complete */
148
boolean isEnd();
149
150
/** Check current generator state */
151
boolean isState(State state);
152
153
/** Check if generator is idle */
154
boolean isIdle();
155
156
/** Reset generator to initial state */
157
void reset();
158
159
/** Set connection persistence */
160
void setPersistent(boolean persistent);
161
162
/** Check if connection should be persistent */
163
boolean isPersistent();
164
165
/** Get current generator state */
166
State getState();
167
168
/**
169
* Generator states
170
*/
171
enum State {
172
/** Initial state, ready to generate */
173
START,
174
175
/** Headers committed, generating body */
176
COMMITTED,
177
178
/** Completing message generation */
179
COMPLETING,
180
181
/** Generation complete */
182
END
183
}
184
185
/**
186
* Generation results indicating next action needed
187
*/
188
enum Result {
189
/** Need chunk buffer for chunked encoding */
190
NEED_CHUNK,
191
192
/** Need response/request info to continue */
193
NEED_INFO,
194
195
/** Need header buffer space */
196
NEED_HEADER,
197
198
/** Ready to flush buffers */
199
FLUSH,
200
201
/** Continue with generation */
202
CONTINUE,
203
204
/** Shutdown output */
205
SHUTDOWN_OUT,
206
207
/** Generation complete */
208
DONE
209
}
210
}
211
```
212
213
### MetaData Classes
214
215
HTTP metadata for requests and responses with header field integration.
216
217
```java { .api }
218
/**
219
* Base metadata for HTTP messages
220
*/
221
class MetaData implements Iterable<HttpField> {
222
/** Create metadata with version and fields */
223
MetaData(HttpVersion version, HttpFields fields);
224
225
/** Create metadata with version, fields, and content length */
226
MetaData(HttpVersion version, HttpFields fields, long contentLength);
227
228
/** Get HTTP version */
229
HttpVersion getHttpVersion();
230
231
/** Get HTTP fields */
232
HttpFields getHttpFields();
233
234
/** Get content length (-1 if unknown) */
235
long getContentLength();
236
237
/** Iterator over HTTP fields */
238
Iterator<HttpField> iterator();
239
240
/**
241
* HTTP request metadata
242
*/
243
static class Request extends MetaData {
244
/** Create request metadata */
245
Request(String method, String uri, HttpVersion version, HttpFields fields);
246
247
/** Create request metadata with HttpURI */
248
Request(String method, HttpURI uri, HttpVersion version, HttpFields fields);
249
250
/** Create request metadata with content length */
251
Request(String method, HttpURI uri, HttpVersion version,
252
HttpFields fields, long contentLength);
253
254
/** Get request method */
255
String getMethod();
256
257
/** Get request URI */
258
HttpURI getHttpURI();
259
260
/** Get request URI as string */
261
String getURI();
262
263
/** Create new request with different URI */
264
Request asImmutable();
265
}
266
267
/**
268
* HTTP response metadata
269
*/
270
static class Response extends MetaData {
271
/** Create response metadata */
272
Response(HttpVersion version, int status, HttpFields fields);
273
274
/** Create response metadata with reason phrase */
275
Response(HttpVersion version, int status, String reason, HttpFields fields);
276
277
/** Create response metadata with content length */
278
Response(HttpVersion version, int status, String reason,
279
HttpFields fields, long contentLength);
280
281
/** Get response status code */
282
int getStatus();
283
284
/** Get response reason phrase */
285
String getReason();
286
287
/** Create immutable copy */
288
Response asImmutable();
289
}
290
}
291
```
292
293
### HttpCompliance Class
294
295
HTTP protocol compliance modes and violation handling.
296
297
```java { .api }
298
/**
299
* HTTP compliance modes and validation
300
*/
301
class HttpCompliance {
302
/** Strict RFC 2616 compliance */
303
static final HttpCompliance RFC2616;
304
305
/** Strict RFC 7230 compliance */
306
static final HttpCompliance RFC7230;
307
308
/** Legacy compatibility mode */
309
static final HttpCompliance LEGACY;
310
311
/** Check if violation is allowed */
312
boolean allows(Violation violation);
313
314
/** Get allowed violations set */
315
Set<Violation> getAllowed();
316
317
/** Get compliance mode name */
318
String getName();
319
320
/**
321
* HTTP compliance violations
322
*/
323
enum Violation {
324
/** Multiple content-length headers */
325
MULTIPLE_CONTENT_LENGTHS,
326
327
/** Transfer-encoding with content-length */
328
TRANSFER_ENCODING_WITH_CONTENT_LENGTH,
329
330
/** Whitespace after field name */
331
WHITESPACE_AFTER_FIELD_NAME,
332
333
/** Case insensitive method */
334
CASE_INSENSITIVE_METHOD,
335
336
/** Duplicate host headers */
337
DUPLICATE_HOST_HEADERS,
338
339
/** No colon after field name */
340
NO_COLON_AFTER_FIELD_NAME;
341
}
342
}
343
```
344
345
**Usage Examples:**
346
347
```java
348
import org.eclipse.jetty.http.*;
349
import java.nio.ByteBuffer;
350
351
// HTTP request parsing
352
class MyRequestHandler implements HttpParser.RequestHandler {
353
private String method;
354
private String uri;
355
private HttpVersion version;
356
private MutableHttpFields headers = new MutableHttpFields();
357
358
@Override
359
public boolean startRequest(String method, String uri, HttpVersion version) {
360
this.method = method;
361
this.uri = uri;
362
this.version = version;
363
return true;
364
}
365
366
@Override
367
public boolean header(HttpField field) {
368
headers.add(field);
369
return true;
370
}
371
372
@Override
373
public boolean headerComplete() {
374
// Headers parsing complete
375
return true;
376
}
377
378
@Override
379
public boolean content(ByteBuffer content) {
380
// Handle request body content
381
return true;
382
}
383
384
@Override
385
public boolean messageComplete() {
386
// Request parsing complete
387
return true;
388
}
389
390
@Override
391
public void badMessage(BadMessageException failure) {
392
// Handle parsing errors
393
}
394
}
395
396
// Create and use parser
397
MyRequestHandler handler = new MyRequestHandler();
398
HttpParser parser = new HttpParser(handler, 8192, HttpCompliance.RFC7230);
399
400
ByteBuffer buffer = ByteBuffer.wrap(
401
"GET /api/users HTTP/1.1\r\nHost: example.com\r\n\r\n".getBytes()
402
);
403
404
boolean complete = parser.parseNext(buffer);
405
406
// HTTP response generation
407
HttpGenerator generator = new HttpGenerator();
408
409
// Create response metadata
410
MutableHttpFields responseHeaders = new MutableHttpFields();
411
responseHeaders.put(HttpHeader.CONTENT_TYPE, "application/json");
412
responseHeaders.put(HttpHeader.CONTENT_LENGTH, "13");
413
414
MetaData.Response response = new MetaData.Response(
415
HttpVersion.HTTP_1_1, 200, "OK", responseHeaders
416
);
417
418
// Generate response
419
ByteBuffer headerBuffer = ByteBuffer.allocate(1024);
420
ByteBuffer contentBuffer = ByteBuffer.wrap("{\"status\":\"ok\"}".getBytes());
421
422
HttpGenerator.Result result = generator.generateResponse(
423
response, false, headerBuffer, null, contentBuffer, true
424
);
425
426
if (result == HttpGenerator.Result.FLUSH) {
427
// Send headerBuffer contents to client
428
headerBuffer.flip();
429
// ... send headerBuffer
430
431
// Send content
432
contentBuffer.flip();
433
// ... send contentBuffer
434
}
435
436
// HTTP response parsing
437
class MyResponseHandler implements HttpParser.ResponseHandler {
438
@Override
439
public boolean startResponse(HttpVersion version, int status, String reason) {
440
// Handle response status line
441
return true;
442
}
443
444
@Override
445
public boolean header(HttpField field) {
446
// Handle response header
447
return true;
448
}
449
450
@Override
451
public boolean content(ByteBuffer content) {
452
// Handle response body
453
return true;
454
}
455
456
@Override
457
public boolean messageComplete() {
458
// Response complete
459
return true;
460
}
461
}
462
463
// Parse HTTP response
464
MyResponseHandler responseHandler = new MyResponseHandler();
465
HttpParser responseParser = new HttpParser(responseHandler);
466
467
ByteBuffer responseData = ByteBuffer.wrap(
468
"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello".getBytes()
469
);
470
471
responseParser.parseNext(responseData);
472
473
// Compliance violation handling
474
ComplianceViolation.Listener violationListener = new ComplianceViolation.Listener() {
475
@Override
476
public void onComplianceViolation(ComplianceViolation.Mode mode,
477
ComplianceViolation violation, String details) {
478
// Log or handle compliance violations
479
System.err.println("Compliance violation: " + violation + " - " + details);
480
}
481
};
482
483
parser.setComplianceViolationListener(violationListener);
484
```