Loading...

Socket (HTTP) connection over Proxy

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

If you need to check that a remote host has a socket open, check following example. This example creates a socket at the HTTP port over your custom network proxy. If the proxy requires authentication, you may override the default Authenticator. Keep in mind that it is only an example!

@Test
public void testSocketConnection() throws Exception {
	SocketAddress addr = new InetSocketAddress("proxy.cinhtau.net", 8080);
	Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
	Socket socket = new Socket(proxy);

	// if you have a proxy user
	Authenticator.setDefault(new Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication("esmeralda", "secret".toCharArray());
		}
	});

	InetSocketAddress dest = new InetSocketAddress("cinhtau.net", 80);
	try {
		socket.connect(dest);
		assertTrue(socket.isConnected());
	} catch (IOException e) {
		LOGGER.error("Network error", e);
	} finally {
		socket.close();
	}
}

Read more → Java Networking and Proxies

Please remember the terms for blog comments.