Last active
September 25, 2021 20:56
-
-
Save aditya-rewari/1994eacbddab1e895d10686d23b24f48 to your computer and use it in GitHub Desktop.
Modify Request and Response through Interceptors at restTemplate in Java Spring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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