0

I'm trying to send a POST request with the following method, and return the HTTP response code upon sending the request.

Code in question:

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}

public int sendRequest() {
    RestTemplate request = new RestTemplate(getClientHttpRequestFactory());
    String URL = buildURL();
    HttpHeaders headers = buildHeaders();
    validatePayload();
    HttpEntity<String> postRequest = new HttpEntity<String>(requestPayload, headers);
    return request.postForObject(URL, postRequest, ResponseEntity.class).getStatusCodeValue();
}

I am generating a ClientHttpRequestFactory so I'm able to set a timeout, and eventually sending a POST by using RestTemplate's postForObject. My issue here is that the program immediately terminates (it runs in the command line) upon sending the POST request, and I'm not able to do anything with the response code. I can't find any documentation online saying that this is expected behavior for postForObject, is there something here that I should be doing differently?

Thanks!

Christian
  • 41
  • 1
  • 3

1 Answers1

1

The issue at hand was that postForObject() was returning null. I had an exception catcher later on that was hiding the issue.

I instead used postForEntity, which did not return null, and I was able to get a HTTP Status code using the following block:

ResponseEntity<String> re = request.postForEntity(URL, postRequest, String.class);
HttpStatus status = re.getStatusCode();
statusCode = status.value();
Christian
  • 41
  • 1
  • 3