如何执行使用vertx跨原点的GET请求?

时间:2019-05-27 09:02:20

标签: java vert.x http-get

我在服务器端将vert.xJAVA一起使用。 当客户端转到http://localhost:8080/hello时,我希望浏览器转到"google.com"。 执行GET请求时出现错误

    router.route("/hello").handler(routingContext -> {
        String url = "google.com";
        WebClient client = WebClient.create(vertx, new WebClientOptions().setSsl(true).setTrustAll(true).setDefaultPort(8080).setKeepAlive(true).setDefaultHost(url));
        client.get(url).as(BodyCodec.string()).send(ar -> {
            if(ar.succeeded()) {
                HttpResponse<String> response = ar.result();
                System.out.println("Got HTTP response body");
                System.out.println(response.body().toString());                 
            }
            else {
                ar.cause().printStackTrace();
            }
        });

    });

错误:

io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection timed out: no further information: google.com/172.217.16.142:8080

1 个答案:

答案 0 :(得分:0)

让我们整理一些东西。

首先,跨源与浏览器有关。您正在发出服务器到服务器的请求,因此此处不相关。

第二,我希望您实际上不需要向google.com发出请求,因为Google实际上试图阻止其他人以这种方式使用其搜索页面。

第三,您使用了url参数两次。一次是设置您的默认主机,第二次是在发出get()请求时。然后,您还将端口设置为8080google.com在我上次检查时不会暴露。

哪个会产生类似的内容:

https://google.com:8080/google.com

要获得更有意义的响应,可以尝试以下代码(我删除了路由部分):

Vertx vertx = Vertx.vertx();

    String url = "api.openweathermap.org";
    WebClient client = WebClient.create(vertx, new WebClientOptions().setDefaultPort(80).setDefaultHost(url));
    client.get("/data/2.5/weather?q=london,uk&units=metric&appid=e38f373567e83d2ba1b6928384435689").as(BodyCodec.string()).send(ar -> {
        if(ar.succeeded()) {
            HttpResponse<String> response = ar.result();
            System.out.println("Got HTTP response body");
            System.out.println(response.body());
        }
        else {
            ar.cause().printStackTrace();
        }
    });