Skip to content

Instantly share code, notes, and snippets.

@shamsimam
Created January 27, 2021 19:05
Show Gist options
  • Select an option

  • Save shamsimam/9c9ef12428c125cc1538db691e42d1ff to your computer and use it in GitHub Desktop.

Select an option

Save shamsimam/9c9ef12428c125cc1538db691e42d1ff to your computer and use it in GitHub Desktop.
Configuring SocketImplFactory for HttpURLConnection
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketImpl;
import java.net.SocketImplFactory;
import java.net.URL;
import java.net.URLConnection;
/**
* @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu)
*/
public class SocketMain {
public static void main(String[] args) throws IOException {
Socket.setSocketImplFactory(new SocketImplFactory() {
@Override
public SocketImpl createSocketImpl() {
try {
System.out.println("SocketMain.createSocketImpl: retrieving SocketImpl constructor");
Constructor socketImplCons = Class.forName("java.net.SocksSocketImpl").getDeclaredConstructor();
socketImplCons.setAccessible(true);
System.out.println("SocketMain.createSocketImpl: creating SocketImpl instance");
SocketImpl si = (SocketImpl) socketImplCons.newInstance();
System.out.println("SocketMain.createSocketImpl: retrieving Socket constructor");
Constructor socketCons = Class.forName("java.net.Socket").getDeclaredConstructor(SocketImpl.class);
socketCons.setAccessible(true);
System.out.println("SocketMain.createSocketImpl: creating Socket instance");
Socket socket = (Socket) socketCons.newInstance(si);
System.out.println("SocketMain.createSocketImpl: configured keep alive on Socket");
socket.setKeepAlive(true);
return si;
} catch (Exception ex) {
throw new IllegalStateException("Unable to create socket", ex);
}
}
});
System.out.println("SocketMain.main: Creating connection");
URL url = new URL("http://www.google.com");
System.out.println("SocketMain.main: Opening URL connection");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
System.out.println("SocketMain.main: Awaiting response code");
final int responseCode = httpUrlConnection.getResponseCode();
System.out.println("SocketMain.main: Response code = " + responseCode);
}
}
SocketMain.main: Creating connection
SocketMain.main: Opening URL connection
SocketMain.main: Awaiting response code
SocketMain.createSocketImpl: retrieving SocketImpl constructor
SocketMain.createSocketImpl: creating SocketImpl instance
SocketMain.createSocketImpl: retrieving Socket constructor
SocketMain.createSocketImpl: creating Socket instance
SocketMain.createSocketImpl: configured keep alive on Socket
SocketMain.main: Response code = 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment