-1

I am writing a web proxy and so far I can read a GET request from a client, format it, and send it to the server, I believe that I have been able to get the response back from the server, but am unsure of how to send the response to the client.

Scanner readClient = new Scanner(new InputStreamReader(client.getInputStream()));               

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Client Request: ");

        String request;
        String host = "";
        String path = "";
        String[] parts = new String[4];

        while((request = bufferedReader.readLine())!= null) { 
            if (request.indexOf("deflate") != -1) {
                break;
            }

            if(request.indexOf("GET") != -1){
                parts = request.split(" ");
                path = parts[1];
                System.out.println("THIS IS THE PATH: " + path);
            }

            if(request.indexOf("Host") != -1){
                parts = request.split(": ");
                host = parts[1]; 
                System.out.println("THIS IS THE HOST: " + host);
            }


            System.out.println(request);
        }

        Socket server = new Socket(host, 80);
        System.out.println("Successfully connected to host: " + host);

        PrintWriter writeServer = new PrintWriter(new DataOutputStream(server.getOutputStream()));          
        InputStream readServer = server.getInputStream();

        writeServer.print("GET " + path + "\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); 
        writeServer.flush();


    OutputStream writeClient = client.getOutputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte buffer[] = new byte[1024];
    for(int s; (s=readServer.read(buffer)) != -1; )
    {
        baos.write(buffer, 0, s);
    }
    byte result[] = baos.toByteArray();

    System.out.println("message sent");

    }
    catch (Exception e) {
        System.out.println("Start Exception: " + e.getMessage());
    }

}   

** Not sure how I am supposed to record edits made to the question, but I have changed my wording and updated my code as well as included more of it.

AndieM
  • 39
  • 8
  • What kind of output do you expect? A text from web page could be the correct response. – Dominik Kunicki Feb 03 '17 at 22:21
  • Play around with wget to see what it is a web server is returning and compare it to what your program is doing. – Duston Feb 03 '17 at 22:39
  • I want the HTTP response. So not the text from the web page. After I get the response I will send it to the client and load the web page. I don't want the text in the terminal, I'm only printing it so I can see what's coming back from the server. – AndieM Feb 04 '17 at 00:48
  • The HTTP response for many requests, and particularly any request you would enter on a browser, _is_ a few headers plus the 'text and formatting' of the webpage; that's exactly what HTML is. But there are lots of valid requests your code will parse completely wrongly. I suggest you learn how HTTP works before you implement it, instead of just randomly guessing. META: Stackexchange records the edit history of Qs and As (but not comments) and displays it on request; it's polite to call people's attention to the fact that you made an edit but you don't need to give details. – dave_thompson_085 Feb 04 '17 at 05:23

2 Answers2

0

You just need to read and copy the input to the output, taking note of the content-length or transfer-encoding headers on the way past, and stop when you exhaust either the content-length or whatever the transfer encoding thinks is the end of the response.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

What kind of errors are you trying to catch? Did some homework last term using Scanner(URL.openStream()) and for anything "not normal" that would display as an error in a browser it would throw an Exception. Here's my catch() statement with some comments, it worked for what I needed at the time.

        // do we have an error?
        catch (Exception ex) {
            // rather than specific exceptions related to the type of 
            // error (network, protocol, webserver content/configuration)
            // the java.net.URL.openStream(URL) seems to return
            // a different message in .getMessage() that you have to
            // parse to figure out what happened.

            // would these messages be different in a different java/jvm implementation?

            String errorMsg=ex.getMessage();

            // nicer errors below
            //System.out.println("Error: "+errorMsg+"\n\r");

            // what makes up our URL? this lets us get the hostname
            // easily as urlParts[2].  
            String[] urlParts=theURL.split("/");

// on DNS failure (use http://aintthere.example.com as test URL)
// Exception.getMessage() seems to return the desired hostname

            if(errorMsg.indexOf(urlParts[2])==0){
                System.out.println("DNS error - invalid or unknown hostname");
            }

// on a 404 error (use http://www.example.com/aintthere) the
// Exception.getMessage() appears to return the URL requested.

            if(errorMsg.indexOf(theURL)==0){
                System.out.println("The requested URL does not exist: "+theURL);
            }

// no route to host or host off line and/or denying connections
            if(errorMsg.indexOf("Connection timed out")==0){
                System.out.println("That host is unreachable or is not allowing connections");
            }

// turns out lots of different SSL errors - invalid certs, self signed certs, mis-matched hostnames, 
// all sorts of things.  seems easier to parse for ".security." in the message since
// they seem to come either from java.security.cert.* or sun.security.*
            if(errorMsg.indexOf(".security.")!=-1){
                System.out.println("Insecure SSL connection attempt - not allowed");
            }

// both 500 (Internal Server Error) and 403 (Access to Resource Forbidden) 
// produce nice standard looking error messages with the error number in them, so
// we check for that.  Why doesn't 404 do that?
            if(errorMsg.indexOf("HTTP response code: 500")!=-1){
                System.out.println("The webserver is suffering from its own issues - Internal Server Error detected");
            }

            if(errorMsg.indexOf("HTTP response code: 403")!=-1){
                System.out.println("Access to that resource is forbidden by the webserver configuration");
            }
        } // end catch
ivanivan
  • 2,155
  • 2
  • 10
  • 11
  • I'm not technically getting any errors, I am just for some reason getting all of the text and formatting of the webpage instead of an HTTP response. I want the page to load once the response from the server is sent to the client. – AndieM Feb 04 '17 at 02:50
  • It would have been simpler and more sensible to have just got the `HttpURLConnection` and then the response code. And more accurate. And independent of exception message texts. – user207421 Feb 04 '17 at 04:56