11package org .example .http ;
22
33import java .nio .charset .StandardCharsets ;
4- import java .util .LinkedHashMap ;
54import java .util .Map ;
65import java .util .TreeMap ;
76
@@ -23,7 +22,8 @@ public void setBody(String body) {
2322 }
2423
2524 public void setHeaders (Map <String , String > headers ) {
26- this .headers = new LinkedHashMap <>(headers );
25+ this .headers = new TreeMap <>(String .CASE_INSENSITIVE_ORDER );
26+ this .headers .putAll (headers );
2727 }
2828
2929 public void setHeader (String name , String value ) {
@@ -35,31 +35,46 @@ public void setContentTypeFromFilename(String filename) {
3535 setHeader ("Content-Type" , mimeType );
3636 }
3737
38- private static final Map <Integer , String > REASON_PHRASES = Map .of (
39- 200 , "OK" ,
40- 201 , "Created" ,
41- 400 , "Bad Request" ,
42- 404 , "Not Found" ,
43- 500 , "Internal Server Error" );
38+ private static final Map <Integer , String > REASON_PHRASES = Map .ofEntries (
39+ Map .entry (200 , "OK" ),
40+ Map .entry (201 , "Created" ),
41+ Map .entry (204 , "No Content" ),
42+ Map .entry (301 , "Moved Permanently" ),
43+ Map .entry (302 , "Found" ),
44+ Map .entry (303 , "See Other" ),
45+ Map .entry (304 , "Not Modified" ),
46+ Map .entry (307 , "Temporary Redirect" ),
47+ Map .entry (308 , "Permanent Redirect" ),
48+ Map .entry (400 , "Bad Request" ),
49+ Map .entry (401 , "Unauthorized" ),
50+ Map .entry (403 , "Forbidden" ),
51+ Map .entry (404 , "Not Found" ),
52+ Map .entry (500 , "Internal Server Error" ),
53+ Map .entry (502 , "Bad Gateway" ),
54+ Map .entry (503 , "Service Unavailable" )
55+ );
4456
4557 public String build (){
4658 StringBuilder sb = new StringBuilder ();
47- String reason = REASON_PHRASES .getOrDefault (statusCode , "OK " );
59+ String reason = REASON_PHRASES .getOrDefault (statusCode , "" );
4860
49- // Status line
50- sb .append (PROTOCOL ).append (" " ).append (statusCode ).append (" " ).append (reason ).append (CRLF );
61+ sb .append (PROTOCOL ).append (" " ).append (statusCode );
62+ if (!reason .isEmpty ()) {
63+ sb .append (" " ).append (reason );
64+ }
65+ sb .append (CRLF );
5166
5267 // User-defined headers
5368 headers .forEach ((k ,v ) -> sb .append (k ).append (": " ).append (v ).append (CRLF ));
5469
55- // Only adds Content-Length if not already set
70+ // Auto-append Content-Length if not set
5671 if (!headers .containsKey ("Content-Length" )) {
5772 sb .append ("Content-Length: " )
5873 .append (body .getBytes (StandardCharsets .UTF_8 ).length )
5974 .append (CRLF );
6075 }
6176
62- // Only adds Connection if not already set
77+ // Auto-append Connection if not set
6378 if (!headers .containsKey ("Connection" )) {
6479 sb .append ("Connection: close" ).append (CRLF );
6580 }
0 commit comments