Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class CookiesHandler implements HttpHandler {
- public void handle(HttpExchange exchange) throws IOException {
- String response = "Hello World!";
- exchange.getResponseHeaders().set("Set-cookie", "ciaseczko2=testoweCiasteczko3; domain=localhost; path=/echo/");
- exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
- String jsonString = JsonWriter.objectToJson(exchange.getResponseHeaders());
- response = JsonWriter.formatJson(jsonString);
- exchange.sendResponseHeaders(200, response.length());
- OutputStream os = exchange.getResponseBody();
- os.write(response.getBytes());
- os.close();
- }
- }
- static class AuthHandler implements HttpHandler {
- public void handle(HttpExchange exchange) throws IOException {
- String response = "Hello World!";
- String user = "u";
- String pass = "p";
- String userAndPass = user + ":" + pass;
- String auth = exchange.getRequestHeaders().getFirst("Authorization");
- if(auth==null){
- notLogin(exchange,response);
- } else {
- if(auth.startsWith("Basic ")){
- String creds = auth.substring(6);
- byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(creds);
- String responseUserAndPassword = new String(decoded, "UTF-8");
- if(responseUserAndPassword.equals(userAndPass)){
- response = "zalogowany";
- exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
- exchange.sendResponseHeaders(200, response.length());
- OutputStream os = exchange.getResponseBody();
- os.write(response.getBytes());
- os.close();
- }else{
- notLogin(exchange,response);
- }
- }
- }
- }
- public void notLogin(HttpExchange exchange, String response) throws IOException{
- exchange.getResponseHeaders().set("WWW-Authenticate", "Basic");
- exchange.sendResponseHeaders(401, 0);
- OutputStream os = exchange.getResponseBody();
- os.write(response.getBytes());
- os.close();
- }
- }
- static class Auth2Handler implements HttpHandler {
- public void handle(HttpExchange exchange) throws IOException {
- String response = "Hello World!";
- response = "Hello " + exchange.getPrincipal().getUsername();
- exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
- exchange.sendResponseHeaders(200, response.length());
- OutputStream os = exchange.getResponseBody();
- os.write(response.getBytes());
- os.close();
- }
- }
- main(){
- ...
- HttpContext auth2 = server.createContext("/auth2/", new Auth2Handler());
- auth2.setAuthenticator(new BasicAuthenticator("user:a, password:p"){
- @Override
- public boolean checkCredentials(String user, String pwd) {
- return user.equals("a") && pwd.equals("p");
- }
- });
- }
Add Comment
Please, Sign In to add comment