Amir Rachum
Amir Rachum

Reputation: 79615

Listening for an HTTP Request

I have an assignment where I need to create a Proxy server, that will manipulate some of the requests/responses it gets, implement caching, etc.

For starters, I want to create the simplest proxy, that simply passes on all requests and responses. I've done some searches online and I am a bit confused on how to listen to requests in a certain port and get the HTTP requests. I've stumbled on the classes Socket, ServerSocket, HttpURLConnection, but I'm not sure how all these interact. I tried to read the docs, but they are all intertwined and a bit hard to understand.

Can you point me in the right direction regarding which classes I should probably use for this assignment, and maybe share a snippet for listening on a port, getting HTTP request headers, etc.?

Upvotes: 8

Views: 5894

Answers (2)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

Here's some introductory Java socket material: http://www.oracle.com/technetwork/java/socket-140484.html

Upvotes: 1

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

Well, I can only assume that your Proxy will be a ServerSocket listening for requests on the HTTP port. You read the request through the server socket input stream. After checking the request is compliant with the proxy's rules you will open a HttpConnection to the real HTTP Server, and using the output stream in the http connection you will forward the client's request, then using the http connection input stream, you read the real HTTP Server's response, which you will ultimately forward back to the client using the socket's output stream.

In the proxy, since you intercept requests and responses you can manipulate them before forwarding.

Sounds right?

Upvotes: 6

Related Questions