55
66import java .util .LinkedHashMap ;
77import java .util .Map ;
8+ import java .util .StringJoiner ;
89import java .util .stream .Collectors ;
910
1011public class HttpResponse {
@@ -13,9 +14,11 @@ public class HttpResponse {
1314 private final Map <String , String > attribute = new LinkedHashMap <>();
1415 private HttpStatus status ;
1516 private String responseBody ;
17+ private Cookie cookie ;
1618
1719 public void setStatus (HttpStatus status ) {
1820 this .status = status ;
21+ cookie = new Cookie ();
1922 }
2023
2124 public void setResponseBody (String responseBody ) {
@@ -26,22 +29,40 @@ public void sendRedirect(String redirectionUrl) {
2629 attribute .put (LOCATION .getValue (), redirectionUrl );
2730 }
2831
29- public void addCookie (String cookie ) {
30- attribute .put (SET_COOKIE . getValue (), cookie );
32+ public void addCookie (String key , String value ) {
33+ cookie .put (key , value );
3134 }
3235
3336 public void setHeader (String key , String value ) {
3437 attribute .put (key , value );
3538 }
3639
40+ private String getAttributeString () {
41+ return String .join ("\r \n " ,
42+ attribute .entrySet ()
43+ .stream ()
44+ .map (entry -> entry .getKey () + ": " + entry .getValue () + " " )
45+ .collect (Collectors .joining ("\r \n " )),
46+ getCookieString ());
47+ }
48+
49+ private String getCookieString () {
50+ Map <String , String > values = cookie .getValues ();
51+
52+ if (values .isEmpty ()) {
53+ return "" ;
54+ }
55+
56+ StringJoiner cookieString = new StringJoiner (";" );
57+ values .forEach ((key , value ) -> cookieString .add (String .format ("%s=%s" , key , value )));
58+
59+ return SET_COOKIE .getValue () + ": " + cookieString ;
60+ }
61+
3762 public String toString () {
3863 return String .join ("\r \n " ,
3964 PROTOCOL + " " + status .getValue () + " " + status .name () + " " ,
40- attribute .entrySet ()
41- .stream ()
42- .map (entry -> entry .getKey () + ": " + entry .getValue () + " " )
43- .collect (Collectors .joining ("\r \n " )),
44- "" ,
65+ getAttributeString (),
4566 responseBody
4667 );
4768 }
0 commit comments