// can use the global CookieHandler used for the first test as the URL's are different
CookieHandler ch = CookieHandler.getDefault();
Map<String,List<String>> header = new HashMap<String,List<String>>();
List<String> values = new LinkedList<String>();
values.add("Test2Cookie=\"TEST2\"; path=\"/test2/\"");
header.put("Set-Cookie2", values);
// preload the CookieHandler with a cookie for our URL // so that it will be sent during the first request
ch.put(url2.toURI(), header);
uc = (HttpURLConnection)url2.openConnection();
resp = uc.getResponseCode(); if (resp != 200) thrownew RuntimeException("Failed: Part 2, Response code is not 200: " + resp);
System.out.println("Response code from Part 2 = 200 OK");
// create HttpServer context for Part 1.
HttpContext ctx = httpServer.createContext("/test/", new MyHandler());
ctx.setAuthenticator( new MyBasicAuthenticator("foo")); // CookieFilter needs to be executed before Authenticator.
ctx.getFilters().add(0, new CookieFilter());
// create HttpServer context for Part 2.
HttpContext ctx2 = httpServer.createContext("/test2/", new MyHandler2());
ctx2.setAuthenticator( new MyBasicAuthenticator("foobar"));
class MyHandler implements HttpHandler { publicvoid handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
Headers reqHeaders = t.getRequestHeaders();
Headers resHeaders = t.getResponseHeaders(); while (is.read () != -1) ;
is.close();
if (!reqHeaders.containsKey("Authorization"))
t.sendResponseHeaders(400, -1);
List<String> cookies = reqHeaders.get("Cookie"); if (cookies != null) { for (String str : cookies) { if (str.equals("Customer=WILE_E_COYOTE"))
t.sendResponseHeaders(200, -1);
}
}
t.sendResponseHeaders(400, -1);
}
}
class MyHandler2 implements HttpHandler { publicvoid handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
Headers reqHeaders = t.getRequestHeaders();
Headers resHeaders = t.getResponseHeaders(); while (is.read () != -1) ;
is.close();
if (!reqHeaders.containsKey("Authorization"))
t.sendResponseHeaders(400, -1);
List<String> cookies = reqHeaders.get("Cookie");
// there should only be one Cookie header if (cookies != null && (cookies.size() == 1)) {
t.sendResponseHeaders(200, -1);
}
t.sendResponseHeaders(400, -1);
}
}
class MyAuthenticator extends java.net.Authenticator { public PasswordAuthentication getPasswordAuthentication () { returnnew PasswordAuthentication("tester", "passwd".toCharArray());
}
}
class MyBasicAuthenticator extends BasicAuthenticator
{ public MyBasicAuthenticator(String realm) { super(realm);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.