-1

我正在编写一个 Web 代理,到目前为止,我可以从客户端读取 GET 请求,对其进行格式化并将其发送到服务器,我相信我已经能够从服务器获取响应,但我不确定如何将响应发送给客户端。

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());
    }

}   

** 不确定我应该如何记录对问题所做的编辑,但我已经更改了措辞并更新了我的代码,并包含了更多内容。

4

2 回答 2

0

您只需要读取输入并将其复制到输出,记下过去的内容长度或传输编码标头,并在您耗尽内容长度或传输编码认为结束时停止响应。

于 2017-02-04T04:57:35.730 回答
-1

你想捕捉什么样的错误?上学期使用 Scanner(URL.openStream()) 做了一些功课,对于任何会在浏览器中显示为错误的“不正常”的东西,它都会抛出异常。这是我的 catch() 语句和一些评论,它满足了我当时的需要。

        // 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
于 2017-02-04T01:49:03.323 回答