Created
February 8, 2014 05:05
-
-
Save sleepdeprecation/8876955 to your computer and use it in GitHub Desktop.
Java HTTPServer's new handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Option One. | |
// | |
import httpserver.*; | |
public class myHandler extends HTTPHandler { | |
public myHandler() throws HTTPException { | |
addGET("/showHeaders", "showHeaders"); | |
addGET("/hello", "sayHello"); | |
addGET("/hello/{String}", "sayHello"); | |
addGET("/hello/{String}/{String}", "sayHello"); | |
// the `*` says optionally. Only okay to have the last parameter be | |
// a star. | |
addGET("/thisAndMore/{*String...}", "thisAndMore"); | |
} | |
public void showHeaders(HTTPResponse resp, HTTPRequest req) { | |
StringBuilder builder = new StringBuilder(); | |
for (String key: req.getHeaders().keySet()) { | |
builder.append(key); | |
builder.append(": "); | |
builder.append(req.getHeaders().get(key)); | |
builder.append("\n\n"); | |
} | |
resp.setBody("Headers: \n\n" + builder.toString()); | |
} | |
public void sayHello(HTTPResponse resp) { | |
resp.setBody("Hello World!"); | |
} | |
public void sayHello(HTTPResponse resp, String name) { | |
resp.setBody("Hello " + name + "!"); | |
} | |
public void sayHello(HTTPResponse resp, String first, String last) { | |
resp.setBody("Hello " + first + " " + last + "!"); | |
} | |
public void thisAndMore(HTTPResponse resp, String... paths) { | |
StringBuilder b = new StringBuilder(); | |
for (String p: paths) { | |
b.append("/"); | |
b.append(p); | |
} | |
resp.setBody("You requested `" + b.toString() + "`"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment