所以我正在玩我自己的Undertow
路径并发布课程。我写了一个实现HttpHandler
接口的类。到目前为止非常直截了当。我的问题。我必须编写一个callback
方法才能访问帖子的xml主体。再一次,没什么大不过的......但是......几个问题......
assuming
这是一个阻塞操作,可能导致请求排队....是吗?exchange.startBlocking()
,然后发送,然后退出。再次......是吗?BlockingHandler
可以实现,其中实现代码不必对io线程进行测试,然后调用exchange.startBlocking()
...是吗?response
,然后使用exchange
进行进一步处理。如果我将代码全部放在callback
处理程序中,会不会更好?谢谢。
public class ApiTaxwareHandler implements HttpHandler {
private static final AtomicLong hitCount = new AtomicLong();
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
//
// Reading the request body is a BLOCKing operation so
// we have to push this thread outside of the io thread
// and then we can block it. the if condition below accomplishes
// that.
// if (exchange.isInIoThread()) {
// exchange.startBlocking();
// exchange.dispatch(this);
// return;
// }
Map<String, Deque<String>> queryParams = exchange.getQueryParameters();
if (queryParams.isEmpty()) {
throw new Exception("Parameter 'key' is missing from the request");
}
long bytesInBody = exchange.getRequestContentLength();
//int bytesInBody = exchange.getInputStream().available();
StringBuilder requestBody = new StringBuilder((int) bytesInBody);
// Low level gobble-d-gook to fully read the request header.
exchange.getRequestReceiver().receiveFullString(new Receiver.FullStringCallback() {
@Override
public void handle(HttpServerExchange exchange, String message) {
//exchange.getResponseSender().send(message);
requestBody.append(message);
log.debug("Leaving FullStringCallback and setting request body StringBuilder");
}
});
String apiKey = queryParams.get("key").getFirst();
String xmlIn = requestBody.toString(); //new Scanner(exchange.getInputStream(), "UTF-8").useDelimiter("\\Z").next();
log.debug("ApiTaxwareHandler.taxLookupHandler.\nPath is: " + exchange.getRequestPath() + "\nQueryParams are: key=" + apiKey + "\nContent size is: " + bytesInBody + "\nRequest body is " + xmlIn);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/xml");
exchange.getResponseSender().send("Responding from " + exchange.getRequestPath() + " Hit Count now: " + hitCount.incrementAndGet());
}