Skip to content

Commit b3cf1d5

Browse files
committed
Always send a never-null JSON response
1 parent 29cef7f commit b3cf1d5

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/main/java/pw/chew/jsonrestapi/RestServer.java

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,10 @@ public void run() {
201201
* @param writer The {@link PrintWriter} to print the response to.
202202
*/
203203
private void respondNotAllowed(PrintWriter writer) {
204-
writer.printf("HTTP/1.2 405 Not Allowed%n%n");
204+
writer.print("HTTP/1.2 405 Not Allowed\n\n"
205+
+ "Content-Type: application/json; charset=utf-8\n"
206+
+ "\n"
207+
+ "{\"success\": false}");
205208
}
206209

207210
/**
@@ -210,7 +213,10 @@ private void respondNotAllowed(PrintWriter writer) {
210213
* @param writer The {@link PrintWriter} to print the response to.
211214
*/
212215
private void respondBadRequest(PrintWriter writer) {
213-
writer.printf("HTTP/1.2 400 Bad Request%n%n");
216+
writer.print("HTTP/1.2 400 Bad Request\n\n"
217+
+ "Content-Type: application/json; charset=utf-8\n"
218+
+ "\n"
219+
+ "{\"success\": false}");
214220
}
215221

216222
/**
@@ -219,7 +225,10 @@ private void respondBadRequest(PrintWriter writer) {
219225
* @param writer The {@link PrintWriter} to print the response to.
220226
*/
221227
private void respondNotFound(PrintWriter writer) {
222-
writer.printf("HTTP/1.2 404 Not Found%n%n");
228+
writer.print("HTTP/1.2 404 Not Found\n\n"
229+
+ "Content-Type: application/json; charset=utf-8\n"
230+
+ "\n"
231+
+ "{\"success\": false}");
223232
}
224233

225234
/**
@@ -228,7 +237,10 @@ private void respondNotFound(PrintWriter writer) {
228237
* @param writer The {@link PrintWriter} to print the response to.
229238
*/
230239
private void respondUnauthorized(PrintWriter writer) {
231-
writer.printf("HTTP/1.2 401 Unauthorized%n%n");
240+
writer.print("HTTP/1.2 401 Unauthorized\n"
241+
+ "Content-Type: application/json; charset=utf-8\n"
242+
+ "\n"
243+
+ "{\"success\": false}");
232244
}
233245

234246
/**
@@ -237,7 +249,12 @@ private void respondUnauthorized(PrintWriter writer) {
237249
* @param writer The {@link PrintWriter} to print the response to.
238250
*/
239251
private void respondOk(PrintWriter writer, String response) {
240-
writer.printf("HTTP/1.2 200 OK%n" + "Content-Type: application/json; charset=utf-8" + "%n%n" + response);
252+
// Don't send a null response.
253+
if (response == null) {
254+
return;
255+
}
256+
257+
writer.print("HTTP/1.2 200 OK\n" + "Content-Type: application/json; charset=utf-8" + "\n\n" + response);
241258
}
242259
}
243260
}

0 commit comments

Comments
 (0)