import java.io.*;
import java.net.*;
import javax.net.ssl.*;

public class WGet_ssl {
    private static Socket         clientSocket = null;
    private static String         nl ="\r\n";    
    private static String         targethost;	
    private static PrintWriter    clientOut = null;    
    private static BufferedReader clientIn  = null;

    
    public static void main(String[] args) {
        if (args.length < 4) {
            System.out.println("Aufruf: java WGet schema host port /file  proxy[0/1]");
            System.out.println("z.B.: java WGet https www.heise.de 443 /index.html 1");
            System.exit(-1);
        }
        String  schema     = args[0];					// http oder https
                targethost = args[1];                   // host
        int     targetport = Integer.parseInt(args[2]); // port
        String  targetfile = args[3];                   // path+file
        String  proxyhost  = "www-cache.htw-dresden.de";
        int	    proxyport  = 3128;
        boolean proxy      = false;
        String  method     = "GET";
        String  res;


        // Test auf Proxy-Nutzung         
        if ( args.length == 4 || Integer.parseInt(args[4]) != 1) {
          	proxyhost = targethost;
          	proxyport = targetport;
        }
        else {
        	proxy = true;           
        	System.out.println("Nutze Proxy...");
        }
        
        try {
            if ( !schema.equals("https") ||  proxy ) {
              clientSocket = new Socket( proxyhost, proxyport );
            }
            else {
              System.out.println("Verbindung über SSLSocket");
              SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
              clientSocket = (SSLSocket) sslFact.createSocket( proxyhost, proxyport);
            }

            // Bietet formatierte Textausgabe u.a. print() + flush = true
            clientOut = new PrintWriter( clientSocket.getOutputStream(), true );
            clientIn  = new BufferedReader(new InputStreamReader( clientSocket.getInputStream() ));

            // für HTTP-Proxy ist absoluter Request notwendig
         // String req1 = "GET " + targetfile + " HTTP/1.1";
            String req1 = method + " " + schema + "://"+ targethost + targetfile + " HTTP/1.1";
            String req2 = "Host: " + targethost;  // + ":80"  
            // echo -n it1:VLIT1 |  base64
            String req4 = "Authorization: Basic aXQxOlZMSVQx";

            
            // TCP-Tunnel mittels CONNECT aufbauen
            if (proxy && schema.equals("https")) connecttoProxy();                        
            
            // Baue Request und sende Leerzeile als Abschlusskennung
            String request = req1 + nl + req2 + nl + req4 + nl + nl;
            // Zeige Request auf Konsole 
            System.out.println("HTTP-Request-Header:\n-------------------");
            System.out.print(request);
            // Sende Request über TCP-Stream
            clientOut.print( request);
            clientOut.flush();
            
            System.out.println("HTTP-Response-Header:\n-------------------");
            while ( !(res = clientIn.readLine()).equals("")  ) {
                System.out.println( res );
            }

            System.out.println("\nHTTP-Daten:\n----------------");

            while ((res = clientIn.readLine()) != null) {
               System.out.println(res);
             }
            System.out.println("\n----------------------\nVerbindung vom Server beendet");
            clientSocket.close();
        }
      catch (IOException ex){ System.out.println(ex);}
    }
    
    
    
    
    static void connecttoProxy() throws IOException {
    	String res;    	
        String req0 = "CONNECT " + targethost + " HTTP/1.1";
        String req2 = "Host: " + targethost;  // + ":80"
        String re   = req0 + nl + req2 + nl + nl;
        clientOut.print( re);
        clientOut.flush(); 
        System.out.print(re);
        
        System.out.println("HTTP-Response-Header:\n-------------------");
        while ( !(res = clientIn.readLine()).equals("")  ) {
            System.out.println( res );
        }
    	System.out.println("\n--> Upgrade auf TLS...\n");
        SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
        clientSocket = (SSLSocket) sslFact.createSocket( clientSocket, clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort() ,true);
        clientOut = new PrintWriter( clientSocket.getOutputStream(), true );
        clientIn  = new BufferedReader(new InputStreamReader( clientSocket.getInputStream() ));            	
    }    
}
	
