HTTP proxy with sockets
Connecting to web means that TCP connection is created at (common) port 80. What happens if proxy is required? In that case, TCP socket connects to the proxy
server and the HTTP Host
header of the request must contain host name of the desired URL. Take a look at the following sample written in Java. It connects
to proxy at 10.63.53.1:3128 and gets initial page of www.alepho.com.
/* ClientHttpProxy.java --------------------- Connects via HTTP proxy. Compile with javac ClientHttpProxy.java */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; class ClientHttpProxy { public static void main(String[] args) { try { // proxy at 10.63.53.1:3128 InetAddress address = InetAddress.getByName("10.63.53.1"); Socket client = new Socket(address, 3128); if (client.isConnected()) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); bw.write("GET http://www.alepho.com/index.php HTTP/1.1\r\n"); bw.write("Host: www.alepho.com\r\n"); bw.newLine(); bw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); String line; do { line = br.readLine(); System.out.println(line); } while (line != null); } } catch (UnknownHostException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } }