2011-04-22 88 views
-1

我需要知道什麼是在下面的代碼HTTP認證JAVA

public class NewClass { 

public static void main(String[] args) { 
    try { 
     while (true) { 
      ServerSocket ss = new ServerSocket(7777); 
      Socket c = ss.accept(); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream())); 
      DataOutputStream writer = new DataOutputStream(c.getOutputStream()); 
      String temp; 

      // read browser Request 
      while ((temp = reader.readLine()) != null) { 
       System.out.println(temp); 
      } 

      // send basic authentication request 
      String response = "WWW-Authenticate: Basic realm=\"test\"\n"; 
      respons += "HTTP/1.1 401 Authorization Required\n"; 
      writer.writeBytes(response); 
      writer.flush(); 

      // receive browser response 
      while ((temp = reader.readLine()) != null) { 
       System.out.println(temp); 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
} 

的問題,當我請求瀏覽器http://localhost:7777,身份驗證對話框不會出現

爲什麼????

也是我正在試圖發送該

String response = "HTTP/1.1 401 Authorization Required\n"; 
        response += "WWW-Authenticate: Basic realm=\"test\"\n"; 

還我發送完整的服務器響應和無裨益

回答

0

的reader.readLine(),直到它到達EOF所以你不會返回null在第一個循環中阻止閱讀並且從不向瀏覽器發送任何內容。

在第一個循環中查找空字符串或null。

while ((temp = reader.readLine()) != null) { 
    if(temp.length() == 0) break; 
    System.out.println(temp); 
} 
+0

我改變了它,但瀏覽器不會出現身份驗證對話框 – ToPMaX 2011-04-22 11:08:35

0

它工作正常

 String response = "WWW-Authenticate: Basic realm=\"test\"\r\n"; 
     respons += "HTTP/1.1 401 Authorization Required\r\n\r\n"; 
     writer.writeBytes(response); 
     writer.flush(); 

但一個一個面臨的問題我如何告訴服務器要等到瀏覽器發送基本的HTTP認證。

在我的情況下瀏覽器請求一個新的http請求。

感謝

+0

這甚至不編譯...響應<-> respons – Fortega 2011-04-22 12:28:21