vert.x: 如何向远程服务器发送请求并得到响应?
vert.x: How to send a request to a remote server and get a response?
我阅读了以下 post 关于使用 vert.x 的 http 客户端的内容:
http://tutorials.jenkov.com/vert.x/http-client.html
我试着写了下面的代码:
public class Main {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new VertxHttpClientVerticle());
}
}
public class VertxHttpClientVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
HttpClient httpClient = vertx.createHttpClient();
httpClient.getAbs("http://api.icndb.com/jokes/random?firstName=John&lastName=Doe",
new Handler<HttpClientResponse>() {
@Override
public void handle(HttpClientResponse httpClientResponse) {
httpClientResponse.bodyHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer buffer) {
System.out.println("Response (" + buffer.length() + "): ");
System.out.println(buffer.getString(0, buffer.length()));
}
});
}
});
}
}
当我 运行 代码时,我没有在控制台中打印任何内容。你知道为什么吗?
httpClient.getAbs
returns 一个 HttpClientRequest
对象,它有一个 end
方法,你需要调用它来触发请求。
如果您想做一个简单的 GET 请求,请查看 HttpClient.getNow
解决方法是:
httpClient.getAbs("http://api.icndb.com/jokes/random?firstName=John&lastName=Doe",
.....
).end()
"end()"使请求被发送。在原始 post 中没有发送请求。
我阅读了以下 post 关于使用 vert.x 的 http 客户端的内容: http://tutorials.jenkov.com/vert.x/http-client.html
我试着写了下面的代码:
public class Main {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new VertxHttpClientVerticle());
}
}
public class VertxHttpClientVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
HttpClient httpClient = vertx.createHttpClient();
httpClient.getAbs("http://api.icndb.com/jokes/random?firstName=John&lastName=Doe",
new Handler<HttpClientResponse>() {
@Override
public void handle(HttpClientResponse httpClientResponse) {
httpClientResponse.bodyHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer buffer) {
System.out.println("Response (" + buffer.length() + "): ");
System.out.println(buffer.getString(0, buffer.length()));
}
});
}
});
}
}
当我 运行 代码时,我没有在控制台中打印任何内容。你知道为什么吗?
httpClient.getAbs
returns 一个 HttpClientRequest
对象,它有一个 end
方法,你需要调用它来触发请求。
如果您想做一个简单的 GET 请求,请查看 HttpClient.getNow
解决方法是:
httpClient.getAbs("http://api.icndb.com/jokes/random?firstName=John&lastName=Doe",
.....
).end()
"end()"使请求被发送。在原始 post 中没有发送请求。