I am trying to extract the cURL String to a JSON file for logging in each request
@RequestMapping(value = "/get/by/id", method = RequestMethod.GET)
public ResponseEntity<Response> getBatchById(HttpServletRequest request, @RequestParam("id") int id) {
Response response = new Response();
HttpStatus httpStatus;
try {
System.out.println(requestToString(request));
response.setResponseCode(CommonVarList.RESPONSE_CODE_SUCCESS);
response.setResponseData(batchService.getBatchById(id));
httpStatus = HttpStatus.OK;
} catch (SQLException e) {
e.printStackTrace();
response.setResponseCode(CommonVarList.RESPONSE_CODE_FAILURE);
httpStatus = HttpStatus.CONFLICT;
} catch (Exception e) {
e.printStackTrace();
response.setResponseCode(CommonVarList.RESPONSE_CODE_FAILURE);
httpStatus = HttpStatus.CONFLICT;
}
return ResponseEntity.status(httpStatus).body(response);
}
This is the method used for extraction
public static String requestToString(HttpServletRequest requestRaw) throws IOException {
HttpServletRequestWrapper request = new HttpServletRequestWrapper(requestRaw);
StringBuilder result = new StringBuilder();
result.append("curl ");
// output method
result.append(request.getMethod()).append(" ");
// output url
result.append("\"").append(request.getRequestURL().toString()).append("\"");
// output headers
for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements(); ) {
String headerName = (String) headerNames.nextElement();
result.append(" -H \"").append(headerName).append(": ").append(request.getHeader(headerName)).append("\"");
}
// output parameters
for (Enumeration<String> parameterNames = request.getParameterNames(); parameterNames.hasMoreElements(); ) {
String parameterName = (String) parameterNames.nextElement();
result.append(" -d \"").append(parameterName).append("=").append(request.getParameter(parameterName)).append("\"");
}
// output body
if ("POST".equalsIgnoreCase(request.getMethod())) {
String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
if (body.length() > 0) {
result.append(" -d \"").append(body).append("\"");
}
}
return result.toString();
}
The above returns the expected for GET requests as following
curl GET "http://localhost:8080/batch/get/by/id" -H "user-agent: PostmanRuntime/7.29.0" -H "accept: /" -H "cache-control: no-cache" -H "postman-token: 5e8884ee-f357-41b4-ad16-9880f90ed5e4" -H "host: localhost:8080" -H "accept-encoding: gzip, deflate, br" -H "connection: keep-alive" -d "id=1"
But whenever a POST request is passed with a body, it throws an error like
java.lang.IllegalStateException: getInputStream() has already been called for this request
Any idea how to resolve this?
PS: My Rest controller class has the following annotations
@RestController
@RequestMapping("/batch")
public class BatchController { ... }