HTTP Authentication JAVA
I need to know what is the problem in the following code
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();
}
}
}
when i request http://localhost:7777 from browser, the authentication dialog does not appear
why ????
also i'm tried to send this
String response = "HTTP/1.1 401 Authorization Required\n";
response += "WWW-Authenticate: Basic realm=\"test\"\n";
also i sent full server resp开发者_运维知识库onse and without benefits
The reader.readLine() will not return null until it reaches the EOF so you are blocked reading in the first loop and never send anything to the browser.
In the first loop look for an empty string or null.
while ((temp = reader.readLine()) != null) {
if( temp.length() == 0 ) break;
System.out.println(temp);
}
It works fine
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();
but one one problem faced me, how to tell server to wait until browser send basic http authentication.
in my case browser request a new http request.
Thanks
精彩评论