How to get the socket used by HttpURLConnection in java

httpconnection, java, sockets

Solution

Sockets are created by Socket Factories. You can write your own SocketFactory, delegating to the original socket factory. In your Socket Factory, you can manipulate the socket. That's one way I can think of for you to get access to the socket, but I'm going to warn you in advance - it's not going to be pretty.

Problem

There is a socket which HttpURLConnection use internally to send data. I know it is now visible from outside, but I am wondering if there's any workaround so that I could get access to this socket (without changing the implementation of HttpURLConnection)? I need this hack to do some instrumentation. Thanks a lot.

Original source