View Javadoc
1   package org.metricshub.http;
2   
3   /*-
4    * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5    * HTTP Java Client
6    * ჻჻჻჻჻჻
7    * Copyright (C) 2023 MetricsHub
8    * ჻჻჻჻჻჻
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   *
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   *
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
21   */
22  
23  /**
24   * Represents an HTTP Response in a simplified way
25   * <ul>
26   * <li>Status code (200, 400, etc.)</li>
27   * <li>Header (Content-type: application/json, etc.)</li>
28   * <li>Body</li>
29   * </ul>
30   */
31  public class HttpResponse {
32  
33  	private int statusCode;
34  	private StringBuilder body;
35  	private StringBuilder header;
36  
37  	/**
38  	 * Create a new HTTP Response
39  	 */
40  	public HttpResponse() {
41  		statusCode = 0;
42  		header = new StringBuilder();
43  		body = new StringBuilder();
44  	}
45  
46  	/**
47  	 * @return HTTP status code (200, 300, etc.)
48  	 */
49  	public int getStatusCode() {
50  		return statusCode;
51  	}
52  
53  	/**
54  	 * Sets the HTTP status code
55  	 *
56  	 * @param code HTTP status code (200, 302, etc.)
57  	 */
58  	public void setStatusCode(int code) {
59  		statusCode = code;
60  	}
61  
62  	/**
63  	 * Get the HTTP header as a single string like below:
64  	 * <pre>
65  	 * Content-type: text/html
66  	 * Content-length: 34094
67  	 * </pre>
68  	 * @return the HTTP header
69  	 */
70  	public String getHeader() {
71  		return header.toString();
72  	}
73  
74  	/**
75  	 * Add one header value
76  	 * @param name Header name (e.g. "Content-type")
77  	 * @param value Header value (e.g. "text/html")
78  	 */
79  	public void appendHeader(String name, String value) {
80  		if (name != null && value != null && !name.isEmpty() && !value.isEmpty()) {
81  			header.append(name).append(": ").append(value).append("\n");
82  		}
83  	}
84  
85  	/**
86  	 * @return the body of the HTTP response
87  	 */
88  	public String getBody() {
89  		return body.toString();
90  	}
91  
92  	/**
93  	 * Append content to the body of the HTTP response
94  	 *
95  	 * @param data Data to append
96  	 */
97  	public void appendBody(String data) {
98  		body.append(data);
99  	}
100 
101 	/**
102 	 * @return the entire HTTP response, header and body
103 	 */
104 	@Override
105 	public String toString() {
106 		return new StringBuilder().append(header).append("\n").append(body).toString();
107 	}
108 }