TcpMonitor is a well-known sub-project of Apache WebServices Commons. It provides a proxy allowing to display the content of HTTP requests and responses. You probably use its Swing user interface but do you know that it can also be used within Java code?
This possibility allows embedding proxy within your unit tests and have everything launched in same time. It actually makes possible to start out your HTTP server, plug your proxy in front of it and execute calls from the client. With this approach, you will be able to display HTTP content…
The jar file of version 1.0 of TcpMon doesn’t allow to do that so we need to get the source code from the trunk and build it. The project uses Maven, has a root Maven project and is structured using modules. In our case, the module that we are interested in is the tcpmon-core one.
Now this is done, you can configure the TcpMon’s proxy from our unit test content as described below:
InterceptorConfigurationBuilder builder = new InterceptorConfigurationBuilder();
InterceptorConfiguration configuration = builder.build();
Interceptor interceptor = new Interceptor(config, new Dump(System.out));
After having configured proxy information, we actually start it using the Interceptor class. The content of HTTP requests and responses can be obtain then though the Dump class. We can obviouly provide our own OutputStream to get content and parse it…
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Interceptor interceptor = new Interceptor(config, new Dump(baos));
//Actually execute call
String content = baos.toString();
System.out.println("content = "+content);
For information, the content contains both HTTP request and response content.