Skip to content

Commit

Permalink
Fix issue 1072
Browse files Browse the repository at this point in the history
  • Loading branch information
xrl2408 committed May 31, 2020
1 parent a7fae95 commit 8f63c06
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -11,3 +11,4 @@ bin
*.iws
reports
.java-version
.DS_Store
26 changes: 22 additions & 4 deletions src/main/java/spark/Request.java
Expand Up @@ -247,28 +247,46 @@ public String ip() {
return servletRequest.getRemoteAddr();
}

//CS304 Issue link: https://github.com/perwendel/spark/issues/1072
/**
* @return the request body sent by the client
*/
public String body() {

if (body == null) {
body = StringUtils.toString(bodyAsBytes(), servletRequest.getCharacterEncoding());
if(!doReadBodyAsBytes) {
try {
bodyAsBytes = IOUtils.toByteArray(servletRequest.getInputStream());
doReadBodyAsBytes = true;
} catch (Exception e) {
LOG.warn("Exception when reading body", e);
}
}
if(bodyAsBytes == null) {
body = "error in readBodyAsBytes";
}
else {
body = StringUtils.toString(bodyAsBytes(), servletRequest.getCharacterEncoding());
}

}

return body;
}

//CS304 Issue link: https://github.com/perwendel/spark/issues/1072
public byte[] bodyAsBytes() {
if (bodyAsBytes == null) {
doReadBodyAsBytes = false;
readBodyAsBytes();
}
return bodyAsBytes;
}

//CS304 Issue link: https://github.com/perwendel/spark/issues/1072
private void readBodyAsBytes() {
try {
bodyAsBytes = IOUtils.toByteArray(servletRequest.getInputStream());
// bodyAsBytes = IOUtils.toByteArray(servletRequest.getInputStream());
// doReadBodyAsBytes = true;
} catch (Exception e) {
LOG.warn("Exception when reading body", e);
}
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/spark/RequestTest.java
Expand Up @@ -63,6 +63,20 @@ public void setup() {
request = new Request(match, servletRequest);

}

//CS304 manually written Issue link: https://github.com/perwendel/spark/issues/1072
@Test
public void testBody() {

final String body = "error in readBodyAsBytes";

when(servletRequest.getProtocol()).thenReturn(body);
String tmp = request.body();

assertEquals("The underlying request protocol should be returned",
body, request.body());

}

@Test
public void queryParamShouldReturnsParametersFromQueryString() {
Expand Down

0 comments on commit 8f63c06

Please sign in to comment.