Skip to content

Instantly share code, notes, and snippets.

@aditya-rewari
Last active September 25, 2021 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aditya-rewari/1994eacbddab1e895d10686d23b24f48 to your computer and use it in GitHub Desktop.
Save aditya-rewari/1994eacbddab1e895d10686d23b24f48 to your computer and use it in GitHub Desktop.
Modify Request and Response through Interceptors at restTemplate in Java Spring
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
String reqBody = new String(body);
byte[] modifiedRequestBody = service.modifyExitingObject(reqBody); // modify as per requirement
ClientHttpResponse response = execution.execute(request, modifiedRequestBody);
String responseBody = new String(response.getBody().readAllBytes());
byte[] modifiedResponseBodyBytes = service.doResponseModification(responseBody); // apply required modification on received response
String modifiedResponseBody = new String(modifiedResponseBodyBytes);
// prepare modified response to be returned
ClientHttpResponse modifiedResponse = new ClientHttpResponse() {
@Override
public HttpHeaders getHeaders() {
return response.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
// The expected modified response body to be populated here
return new ByteArrayInputStream(modifiedResponseBody.getBytes());
}
@Override
public HttpStatus getStatusCode() throws IOException {
return response.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return response.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return response.getStatusText();
}
@Override
public void close() {
}
};
return modifiedResponse;
}
@Bean
public RestTemplate getInterceptedRestTemplate() {
RestTemplate restTemplate =
new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(interceptor); // use above defined interceptor here
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment