Modifying Body Content of Response to Client
To modify the request body in the pre-processing stage, employ the content source and content producer to read from and write to the HTTP request.
Procedure
-
Get
HTTPClientResponsefrom theCallcontextof an event. -
Get
ContentSourcefrom theHTTPClientResponse. -
Get
InputStreamfrom theContentSourceand convert it into a String form. -
Add or modify the string content and set the body of
HTTPServerResponsewith the new content. (HTTPServerResponse can be obtained fromTrafficManagerResponseof the call context of an event.)
private static final String CUSTOM_HEADER="X-CUSTOM-HEADER";
private static final String CUSTOM_HEADER_VALUE="POST-PROCESSED";
@Override
public void handleEvent(TrafficEvent event) {
if(event instanceof PostProcessEvent){
Logger.debug(AddHeaderPostProcessor.class, "Handling post process event");
doPostProcessEvent((PostProcessEvent) event);
}
}
private void doPostProcessEvent(PostProcessEvent event) {
ExtendedAttributes attrs = (event).getKey().getExtendedAttributes();
String strAllowed = attrs.getValue("EAV_CallAllowed");
if(strAllowed != null && !Boolean.parseBoolean(strAllowed)){
event.getCallContext().getResponse().getHTTPResponse().setStatusCode(401);
event.getCallContext().getResponse().getHTTPResponse().setBody(new
StringContentProducer("{\"error\":\"Call not allowed for this key\"}"));
event.getCallContext().getResponse().setComplete();
}
}
note
Refer to the working code in examples/ AddBodyContentPostProcessor.java.