vert.x:如何将请求发送到远程服务器并获得响应?

时间:2017-05-09 21:34:29

标签: httpclient vert.x

我阅读了以下有关带有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()));
                    }
                });
            }
        });
    }
}

当我运行代码时,我不会在控制台中打印任何内容。你知道为什么吗?

2 个答案:

答案 0 :(得分:1)

httpClient.getAbs会返回一个HttpClientRequest对象,该对象需要调用end方法来触发请求。

如果您想要执行简单的GET请求,请查看HttpClient.getNow

答案 1 :(得分:0)

解决方案是:

httpClient.getAbs("http://api.icndb.com/jokes/random?firstName=John&lastName=Doe",
    .....
).end()

&#34; end()&#34;发出请求。在原始帖子中没有发送请求。