title: AOP solution for Logging callouts - outgoing http request and responses
body: <p>I am developing a spring boot application and implement a javax.servlet.Filter (using HttpServletResponseWrapper and HttpServletRequestWrapper) to intercept incoming http requests and log them. While this works great for incoming calls, I am not sure how to intercept outgoing calls (callouts). I am not sure I bumped into a SO page explaining this for a non SOAP client.</p>
  
  <p>I tried extending the HandlerInterceptorAdapter class and overriding the preHandle() and postHandle() methods but these seem to intercept the incoming requests. I am interested in the outgoing calls.</p>
  
  <p>What would be an aop solution to intercept and log client / outgoing  http requests and responses or callouts?</p>
  
  <p>The callouts use the below helper class:</p>
  
  <pre><code>import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.StatusLine;
  import org.apache.http.client.HttpClient;
  import org.apache.http.client.methods.HttpGet;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.methods.HttpRequestBase;
  import org.apache.http.entity.StringEntity;
  
  @Service
  public class CalloutService {
  @Autowired
  protected HttpClient httpClient;
  
  public CalloutService() {
  }
  
  private MessageResponse sendRequest(HttpRequestBase request, Map&lt;String, String&gt; httpHeaders) throws IOException {
      addHttpHeaders(request, getDefaultHeaders());
      addHttpHeaders(request, httpHeaders);
      HttpResponse response = httpClient.execute(request);
      HttpEntity entity = response.getEntity();
      String responseBody = IOUtils.toString(entity.getContent(), "UTF-8");
      StatusLine statusLine = response.getStatusLine();
      return new MessageResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);
    }
  }
  </code></pre>