1+ package org .example .httpparser ;
2+
3+ import java .io .BufferedReader ;
4+ import java .io .IOException ;
5+ import java .io .InputStream ;
6+ import java .io .InputStreamReader ;
7+ import java .util .HashMap ;
8+ import java .util .Map ;
9+
10+ public class HttpParser {
11+ public HttpRequest parse (InputStream in ) throws IOException {
12+ BufferedReader reader = new BufferedReader (new InputStreamReader (in ));
13+
14+ // 1. Request Line
15+ String requestLine = reader .readLine ();
16+ if (requestLine == null || requestLine .isEmpty ()) {
17+ throw new IOException ("The request is empty" );
18+ }
19+
20+ String [] parts = requestLine .split (" " );
21+ String method = parts [0 ];
22+ String fullPath = parts [1 ];
23+ String version = parts [2 ];
24+
25+ String path ;
26+ String query = null ;
27+
28+ int qIndex = fullPath .indexOf ('?' );
29+ if (qIndex >= 0 ) {
30+ path = fullPath .substring (0 , qIndex );
31+ query = fullPath .substring (qIndex + 1 );
32+ } else {
33+ path = fullPath ;
34+ }
35+
36+ // 2. Headers
37+ Map <String , String > headers = new HashMap <>();
38+ String line ;
39+ while (!(line = reader .readLine ()).isEmpty ()) {
40+ int colon = line .indexOf (':' );
41+ String key = line .substring (0 , colon ).trim ();
42+ String value = line .substring (colon + 1 ).trim ();
43+ headers .put (key , value );
44+ }
45+
46+ // 3. Body
47+ byte [] body = new byte [0 ];
48+ if (headers .containsKey ("Content-Length" )) {
49+ int length = Integer .parseInt (headers .get ("Content-Lenght" ));
50+ body = in .readNBytes (length );
51+ }
52+
53+ return new HttpRequest (method , path , query , version , headers , body );
54+
55+ }
56+ }
0 commit comments