2017-02-03 106 views
-1

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

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

} 

**不知道我应该如何记录的问题所做出的编辑,但我已经改变了我的措辞,并更新了我的代码,以及包含更多。

+0

你期望什么样的输出?来自网页的文字可能是正确的回应。 –

+0

玩弄wget,看看它是一个Web服务器正在返回并将其与您的程序正在做的事情进行比较。 – Duston

+0

我想要HTTP响应。所以不是来自网页的文字。收到响应后,我会将它发送给客户端并加载网页。我不希望终端中的文本,我只是打印它,以便我可以看到从服务器返回的内容。 – AndieM

回答

-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 
+0

我在技术上没有得到任何错误,我只是出于某种原因获取网页的所有文本和格式,而不是HTTP响应。一旦服务器的响应被发送到客户端,我希望加载页面。 – AndieM

+0

刚刚得到'HttpURLConnection'和响应代码会更简单也更明智。而且更准确。独立于例外消息文本。 – EJP

0

你只需要阅读和输入复制到输出,注意到内容长度或传输编码头在过去的方式,并停止当你用尽任何内容长度或任何传输编码认为是响应的结束。

相关问题