Forward HttpServletRequest to a different server

http, java, servlets, spring, spring-mvc

Solution

Unfortunately there is no easy way to do this. Basically you'll have to reconstruct the request, including:

- correct HTTP method

- request parameters

- requests headers (`HTTPUrlConnection` doesn't allow to set arbitrary user agent, "`Java/1.*`" is always appended, you'll need HttpClient)

- body

That's a lot of work, not to mention it won't scale since each such proxy call will occupy one thread on your machine.

My advice: use raw sockets or netty and intercept HTTP protocol on the lowest level, just replacing some values (like `Host` header) on the fly. Can you provide more context, why so you need this?

Problem

I got a `HttpServletRequest` request in my Spring Servlet which I would like to forward AS-IS (i.e. GET or POST content) to a different server. What would be the best way to do it using Spring Framework? Do I need to grab all the information and build a new `HTTPUrlConnection`? Or there is an easier way?

Original source

Related problems