Java Reference
In-Depth Information
}
}
class Handler implements HttpHandler
{
@Override
public void handle(HttpExchange xchg) throws IOException
{
Headers headers = xchg.getRequestHeaders();
Set<Map.Entry<String, List<String>>> entries = head-
ers.entrySet();
StringBuffer response = new StringBuffer();
for (Map.Entry<String, List<String>> entry: entries)
response.append(entry.toString()+"\n");
xchg.sendResponseHeaders(200, response.length());
OutputStream os = xchg.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
The handler demonstrates the following
HttpExchange
abstract methods:
•
Headers getRequestHeaders()
returnsanimmutablemapofanHTTP
request's headers.
•
void sendResponseHeaders(int rCode, long respon-
seLength)
beginstosendaresponsebacktotheclientusingthecurrentset
of response headers and
rCode
's numeric code; 200 indicates success.
•
OutputStream getResponseBody()
returnsanoutputstreamtowhich
the response's body is output. This method must be called after calling
sendResponseHeaders()
.
Collectively, these methods are used to echo an incoming request's headers back to
the client.
Figure 11-5
showsthese headers after issent tothe server.Don'tforget that
placing any path items before
echo
results in a 404 Not Found page.