Send no response body when the response status code is 204. (#1610)

Affects issues:
- Fixed #1605
This commit is contained in:
FluxCapacitor 2020-10-15 14:03:13 -04:00 committed by GitHub
parent f6b4c29589
commit 0ac5ad6f23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 9 additions and 3 deletions

View File

@ -132,6 +132,10 @@ public class ResponseBuilder {
*/
public Response build() {
byte[] content = response.bytes;
if(content == null && response.code == 204) {
// HTTP Code 204 requires no response, so there is no need to validate it.
return response;
}
exceptionIf(content == null, "Content not defined for Response");
String mimeType = getMimeType();
exceptionIf(content.length > 0 && mimeType == null, "MIME Type not defined for Response");

View File

@ -158,7 +158,7 @@ public class ResponseResolver {
private Response tryToGetResponse(Request request) {
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
return Response.builder().setStatus(204).setContent(new byte[0]).build();
return Response.builder().setStatus(204).build();
}
Optional<WebUser> user = request.getUser();

View File

@ -45,7 +45,7 @@ public class ResponseSender {
public void send() throws IOException {
setResponseHeaders();
if ("HEAD".equals(exchange.getRequestMethod())) {
if ("HEAD".equals(exchange.getRequestMethod()) || response.getCode() == 204) {
sendHeadResponse();
} else if ("bytes".equalsIgnoreCase(response.getHeaders().get("Accept-Ranges"))) {
sendRawBytes();
@ -91,7 +91,9 @@ public class ResponseSender {
}
private void beginSend() throws IOException {
exchange.sendResponseHeaders(response.getCode(), 0);
// Return a content length of -1 for HTTP code 204 (No content)
// and HEAD requests to avoid warning messages.
exchange.sendResponseHeaders(response.getCode(), (response.getCode() == 204 || "HEAD".equals(exchange.getRequestMethod())) ? -1 : 0);
}
private void sendRawBytes() throws IOException {