Improve handling of the Content-Length header

Previously, some MockMvc-specific logic would add a Content-Length
header to every request that had content. This led to the curl request
snippet containing a -H option for the Content-Length header. This is
unnecessary as curl will automatically generate a Content-Length
header based on the data that's being sent to the server. A secondary
problem was the inconsistent automatic addition of a Content-Length
header; the header was not automatically added to responses.

This commit remove the MockMvc-specific logic in favour of some new
logic in the core project to automatically add a Content-Length header
to both requests and responses. The curl request snippet has been
updated to supress the header in favour of curl's automatic
generation.

Closes gh-111
This commit is contained in:
Andy Wilkinson
2015-09-28 11:14:58 +01:00
parent cc0edcb901
commit 5da4bee3c6
11 changed files with 81 additions and 67 deletions

View File

@@ -115,8 +115,10 @@ public class CurlRequestSnippet extends TemplatedSnippet {
private void writeHeaders(HttpHeaders headers, PrintWriter writer) {
for (Entry<String, List<String>> entry : headers.entrySet()) {
for (String header : entry.getValue()) {
writer.print(String.format(" -H '%s: %s'", entry.getKey(), header));
if (!HttpHeaders.CONTENT_LENGTH.equalsIgnoreCase(entry.getKey())) {
for (String header : entry.getValue()) {
writer.print(String.format(" -H '%s: %s'", entry.getKey(), header));
}
}
}
}

View File

@@ -35,7 +35,18 @@ abstract class AbstractOperationMessage {
AbstractOperationMessage(byte[] content, HttpHeaders headers) {
this.content = content == null ? new byte[0] : content;
this.headers = headers;
this.headers = createHeaders(content, headers);
}
private static HttpHeaders createHeaders(byte[] content, HttpHeaders input) {
HttpHeaders headers = new HttpHeaders();
if (input != null) {
headers.putAll(input);
}
if (content != null && content.length > 0 && headers.getContentLength() == -1) {
headers.setContentLength(content.length);
}
return headers;
}
public byte[] getContent() {

View File

@@ -63,9 +63,12 @@ public class ContentModifyingOperationPreprocessor implements OperationPreproces
private HttpHeaders getUpdatedHeaders(HttpHeaders headers, byte[] updatedContent) {
HttpHeaders updatedHeaders = new HttpHeaders();
updatedHeaders.putAll(headers);
if (updatedHeaders.getContentLength() > -1) {
if (updatedContent.length > 0) {
updatedHeaders.setContentLength(updatedContent.length);
}
else {
updatedHeaders.remove(HttpHeaders.CONTENT_LENGTH);
}
return updatedHeaders;
}