Reputation: 740
I would like to basically sniff HTTP/HTTPS requests and responses from my computer to a remote URL (basically a REST API). I understand there are plenty of tools that will help me get what I want, but I have to kind of write a utility to do this in Java (as this's going to be used by some applications we are developing).
What I want to do is set up a proxy (or a reverse proxy - my understanding of the terms is limited here), through which I route all my requests to real APIs. This proxy must Capture the Request body (in case of a POST or PUT) and forward the request to the real API, capture its response and send it back to the client.
I came across Undertow, using which I was able to create and run a Reverse Proxy using its LoadBalancingProxyClient
proxy client. But I have a few questions here.
Assume my API is http://myrealapplication.com/rest/operation1
, and I want to POST a JSON to this API.
I have created a proxy server as follows:
LoadBalancingProxyClient loadBalancer = new LoadBalancingProxyClient();
loadBalancer.addHost(new URI("http://myrealapplication.com"));
loadBalancer.setConnectionsPerThread(20);
Undertow reverseProxy = Undertow.builder()
.addHttpListener(8990, "localhost")
.setIoThreads(4)
.setHandler(Handlers.requestDump(new ProxyHandler(loadBalancer, 3000, null)))
.build();
reverseProxy.start();
So once I've started my Reverse Proxy server, there are two things:
http://localhost:8990/rest/operation1
, which may not be acceptable, as what we are expecting to do is to set up localhost:8990
as a Proxy, and keep my URL as http://myrealapplication.com/rest/operation1
, so that it looks to the end client as the response is coming from the actual API.Can I use undertow to achieve this? Or are there any other tools which expose a Java API which I can use in my programs?
Please help!
Thanks, Sriram
Upvotes: 2
Views: 2365
Reputation: 1595
I think that what you are actually looking for is a Forward Proxy. Here is sample code which would help you to create one.
public class ForwardProxyWithUndertow {
public static void main( String[] args ) {
final HttpHandler forwardProxyHandler = new ConnectHandler(ForwardProxyWithUndertow::handleNotFound );
Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler( forwardProxyHandler )
.build()
.start();
}
static void handleNotFound( HttpServerExchange e ){
e.setStatusCode(404);
e.endExchange();
}
}
Hope it helps! ;)
Upvotes: 1