1

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 { ... }
Vizard
  • 149
  • 1
  • 12
  • Can you include more of your code, or a [a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)? It worked for me with a simple Spring Boot RestController. – badjr Feb 21 '22 at 01:17
  • Do you also have a `@RequestMapping` for the POST? Also for the controller class, can you include the class declaration as well (there may be some annotations added that are influencing this behavior)? – badjr Feb 21 '22 at 16:37
  • 1
    You're reading the request body inside `requestToString()`, that consumes the stream and it cannot be read again. You need to wrap the request object in a custom one (or look around for an already made implementation). You can look at [HttpRequestWrapper](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/client/support/HttpRequestWrapper.html) as a start. – watery Feb 21 '22 at 18:45
  • @watery Hi thanks for the suggestion. I used the HttpRequestWrapper to wrap the request inside the static method but the error is still there. Updated the question as well – Vizard Feb 21 '22 at 20:13
  • 1
    Fixed it with [this answer](https://stackoverflow.com/a/34806876/9483238) – Vizard Feb 22 '22 at 20:04

0 Answers0