2011-04-22 112 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