java Rest服务调用未触发处理程序
我正在用vert写一份申请书。x和Java
我有一门课程,我在其中注册了基本休息服务的终点:
private void setRoutes(Router router){
router.route("/*").handler(StaticHandler.create());
router.get("/service").handler(req -> {
getServices();//Call to Database and populate the services
List<JsonObject> jsonServices = services
.entrySet()
.stream()
.map(service ->
new JsonObject()
.put("name", service.getKey())
.put("status", service.getValue()))
.collect(Collectors.toList());
req.response().setStatusCode(200)
.putHeader("content-type", "application/json")
.end(new JsonArray(jsonServices).encode());
});
router.post("/service").handler(req -> {
JsonObject jsonBody = req.getBodyAsJson();
addService(jsonBody);//Persist the service
//services.put(jsonBody.getString("url"), "UNKNOWN");
req.response()
.putHeader("content-type", "text/plain")
.end("OK");
});
我正在对Get/服务端点进行HTTP Get调用,如下所示,并尝试获取响应状态代码。但是每次线程卡在conn.getResponseCode()上时,都不会发生任何事情
还有我的路由器。获取(“/service”)。处理程序从未被调用,在调试模式下,我可以看到ResponseCode的值为-1。从邮递员当我点击这个网址,我能够得到正确的结果,也从浏览器我可以得到正确的结果。为什么不返回状态代码200。此外,它也不去捕捉或最后块
private void checkService(String key,DBConnector connector) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://localhost:8080/service");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(50);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//Update the status of the URL to OK
connector.query("UPDATE service set status = 'OK' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to OK");
}
else {
//Handle this properly later
System.out.println("Failed to update the status to OK");
}
});
}
else {
connector.query("UPDATE service set status = 'FAIL' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to fail");
}
else {
//Handle this properly later
System.out.println("Failed to update the status to fail");
}
});
}
}
catch (Exception e) {
e.printStackTrace();
//Code to set the status to FAIL
connector.query("UPDATE service set status = 'FAIL' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to fail");
}
else {
//Handle this properly later
System.out.println("Failed to update the status to fail");
}
});
}
finally {
System.out.println("INSIDE FINALLY");
}
System.out.println(" Done");
}
# 1 楼答案
尝试在路由之后设置静态处理程序:
Vertx路由器按照连接的顺序匹配路由。在当前状态下,所有匹配
/*
的请求(包括/service
)都将被匹配并传递给静态处理程序https://vertx.io/docs/vertx-web/java/#_route_order