20-CS-694 Advanced Programming Techniques Spring 2012
Networking

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous      Next     RProxyServer.java     URLConnection Class     URL Class     MalformedURLException Class      All lectures

Browser Proxy Server

This is a proxy Server for typical web browsers. Your browser's network settings need to be configured to use it. In the case of Firefox, select the "Edit" menu and click on preferences. Click on the "Advanced" tab then the "Network" tab. Click on connection "Settings." Click on "Manual Proxy Configuration" and under "HTTP Proxy" enter "localhost" and "8690" for the "Port." Click on OK to save the configuration. The browser now points to the proxy server below, if it is running. To do that, compile the code and run "java RProxyServer." This is intended for demonstration purposes only and cannot serve all files correctly.
import java.io.*;
import java.net.*;

class RPS extends Thread {
   Socket incoming;
   URL url;
   OutputStream out = null;
   URLConnection rms = null;
   FileOutputStream file = null;
   String protocol = null;
   String urlname = null;
   
   RPS (Socket incoming) { this.incoming = incoming; }
   
   public String urlDecode(String in) {
      StringBuffer out = new StringBuffer(in.length());
      int i = 0;
     
      while (i < in.length()) {
         char ch = in.charAt(i);
         i++;
         if (ch == '+') ch = ' ';
         else if (ch == '%') {
            ch = (char)(Integer.parseInt("0x"+ in.substring(i, i + 2)));
            i++;
         }
         out.append(ch);
      }
      return new String(out);      
   }

   String getPath(String msg) {
      if (msg.length() == 0 || msg.substring(0,3) == "GET") return null;
      String path = msg.substring(msg.indexOf(' ')+1);
      path = path.substring(0, path.indexOf(' '));
      return path;
   }
   
   void sendHeader(OutputStream os, URLConnection rms) {
      String header;
      int i=0;
      
      System.out.println("Header to client:");
      PrintWriter fos = new PrintWriter(os, true);
      while ((header = rms.getHeaderField(i++)) != null) {
         fos.print(header);
         System.out.println(header);
      }
   }
   
   public void run () {
      try {
         InputStream ins = incoming.getInputStream();
         BufferedReader in = new BufferedReader(new InputStreamReader(ins));
         out = incoming.getOutputStream();

         String request = in.readLine();
         urlname = getPath(request);
         urlname = urlDecode(urlname);
         System.out.println("URL: "+urlname);
         String a = in.readLine();
         while (!a.equals("")) {
            System.out.println("Got: "+a);
            a = in.readLine();
         }
         System.out.println("----------------------------");
              
         try {
            // Hopefully hit the URL
            url = new URL(urlname);
            rms = url.openConnection();
         }
         catch (MalformedURLException e) {
            String fullurl;
            // Check if a protocol is specified.  If not, assume http   
            int pos = urlname.indexOf("://");
            if (pos < 0) protocol = "http";
            else protocol = urlname.substring(0, pos);
            if (pos < 0) pos = 0; else pos += 3;

            // Assemble a reasonable URL
            int pos1 = urlname.indexOf(":", pos);
            if (pos == pos1)
               fullurl = protocol+"://localhost"+urlname.substring(pos);
            else
               fullurl = protocol+"://"+urlname.substring(pos);
            
            // Hit the URL
            url = new URL(fullurl);
            rms = url.openConnection();
         }
         
         file = new FileOutputStream("file");
         sendHeader(out, rms);
         InputStream rmms = rms.getInputStream();
         int sz = rmms.available();

         while ((sz = rmms.available()) > 0) {
            byte message[] = new byte[sz];
            rmms.read(message, 0, sz);
            out.write(message, 0, sz);
            file.write(message, 0, sz);
         }
      }
      catch (ArrayIndexOutOfBoundsException ai) {
         PrintWriter fos = new PrintWriter(out, true);
         fos.println("<h1>No URL specified</h1>");
      }
      catch (ConnectException ce) {
         PrintWriter fos = new PrintWriter(out, true);            
         fos.println("<h1>Connection Refused</h1>");
      }
      catch (UnknownHostException uh) {
         PrintWriter fos = new PrintWriter(out, true);            
         fos.println("<h1>Unknown Host: "+urlname+"</h1>");
      }
      catch (Exception ex) {
         PrintWriter fos = new PrintWriter(out, true);            
         fos.println("<h1>Unknown Error: " + ex +"</h1>");
      }
      try {
         incoming.close();
      }
      catch (Exception e) {
         PrintWriter fos = new PrintWriter(out, true);            
         fos.println("<h1>Cannot close connection</h1>");
      }
   }
}

public class RProxyServer {
   public static void main (String arg[]) {
      ServerSocket s;
      try {
         s = new ServerSocket(8690);
         System.out.println("Server started and listening on port "+s.getLocalPort());
         while (true) {
            Socket incoming = s.accept( );
            new RPS (incoming).start();
         }
      }
      catch (Exception e) {
         System.out.println(e.toString());
      }
   }
}