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

你只需要閱讀和輸入複製到輸出,注意到內容長度或傳輸編碼頭在過去的方式,並停止當你用盡任何內容長度或任何傳輸編碼認爲是響應的結束。

相關問題