Search in sources :

Example 51 with HttpClient

use of io.vertx.core.http.HttpClient in project vertx-examples by vert-x3.

the class MyJUnitTest method test1.

@Test
public void test1(TestContext context) {
    // Send a request and get a response
    HttpClient client = vertx.createHttpClient();
    Async async = context.async();
    client.getNow(8080, "localhost", "/", resp -> {
        resp.bodyHandler(body -> {
            context.assertEquals("foo", body.toString());
            client.close();
            async.complete();
        });
    });
}
Also used : Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient) Test(org.junit.Test)

Example 52 with HttpClient

use of io.vertx.core.http.HttpClient in project vertx-examples by vert-x3.

the class VertxUnitTest method run.

// Not yet detected
@CodeTranslate
public void run() {
    TestOptions options = new TestOptions().addReporter(new ReportOptions().setTo("console"));
    TestSuite suite = TestSuite.create("io.vertx.example.unit.test.VertxUnitTest");
    suite.before(context -> {
        vertx = Vertx.vertx();
        vertx.createHttpServer().requestHandler(req -> req.response().end("foo")).listen(8080, context.asyncAssertSuccess());
    });
    suite.after(context -> {
        vertx.close(context.asyncAssertSuccess());
    });
    // Specifying the test names seems ugly...
    suite.test("some_test1", context -> {
        // Send a request and get a response
        HttpClient client = vertx.createHttpClient();
        Async async = context.async();
        client.getNow(8080, "localhost", "/", resp -> {
            resp.bodyHandler(body -> context.assertEquals("foo", body.toString("UTF-8")));
            client.close();
            async.complete();
        });
    });
    suite.test("some_test2", context -> {
        // Deploy and undeploy a verticle
        vertx.deployVerticle("io.vertx.example.unit.SomeVerticle", context.asyncAssertSuccess(deploymentID -> {
            vertx.undeploy(deploymentID, context.asyncAssertSuccess());
        }));
    });
    suite.run(options);
}
Also used : CodeTranslate(io.vertx.codetrans.annotations.CodeTranslate) TestSuite(io.vertx.ext.unit.TestSuite) Async(io.vertx.ext.unit.Async) TestOptions(io.vertx.ext.unit.TestOptions) HttpServer(io.vertx.core.http.HttpServer) Vertx(io.vertx.core.Vertx) ReportOptions(io.vertx.ext.unit.report.ReportOptions) HttpClient(io.vertx.core.http.HttpClient) TestSuite(io.vertx.ext.unit.TestSuite) TestOptions(io.vertx.ext.unit.TestOptions) Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient) ReportOptions(io.vertx.ext.unit.report.ReportOptions) CodeTranslate(io.vertx.codetrans.annotations.CodeTranslate)

Example 53 with HttpClient

use of io.vertx.core.http.HttpClient in project vertx-examples by vert-x3.

the class WgetCommand method start.

@Override
public void start() throws Exception {
    // Create the wget CLI
    CLI cli = CLI.create("wget").setSummary("Wget implemented with Vert.x HTTP client").addArgument(new Argument().setIndex(0).setArgName("http-url").setDescription("the HTTP uri to get"));
    // Create the command
    Command helloWorld = CommandBuilder.command(cli).processHandler(process -> {
        URL url;
        try {
            url = new URL(process.commandLine().getArgumentValue(0));
        } catch (MalformedURLException e) {
            process.write("Bad url\n").end();
            return;
        }
        HttpClient client = process.vertx().createHttpClient();
        process.write("Connecting to " + url + "\n");
        int port = url.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpClientRequest req = client.get(port, url.getHost(), url.getPath());
        req.exceptionHandler(err -> {
            process.write("wget: error " + err.getMessage() + "\n");
            process.end();
        });
        req.handler(resp -> {
            process.write(resp.statusCode() + " " + resp.statusMessage() + "\n");
            String contentType = resp.getHeader("Content-Type");
            String contentLength = resp.getHeader("Content-Length");
            process.write("Length: " + (contentLength != null ? contentLength : "unspecified"));
            if (contentType != null) {
                process.write("[" + contentType + "]");
            }
            process.write("\n");
            process.end();
        });
        req.end();
    }).build(vertx);
    ShellService service = ShellService.create(vertx, new ShellServiceOptions().setTelnetOptions(new TelnetTermOptions().setHost("localhost").setPort(3000)));
    CommandRegistry.getShared(vertx).registerCommand(helloWorld);
    service.start(ar -> {
        if (!ar.succeeded()) {
            ar.cause().printStackTrace();
        }
    });
}
Also used : TelnetTermOptions(io.vertx.ext.shell.term.TelnetTermOptions) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) ShellService(io.vertx.ext.shell.ShellService) CommandBuilder(io.vertx.ext.shell.command.CommandBuilder) Argument(io.vertx.core.cli.Argument) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Command(io.vertx.ext.shell.command.Command) CLI(io.vertx.core.cli.CLI) ShellServiceOptions(io.vertx.ext.shell.ShellServiceOptions) CommandRegistry(io.vertx.ext.shell.command.CommandRegistry) AbstractVerticle(io.vertx.core.AbstractVerticle) Runner(io.vertx.example.util.Runner) HttpClient(io.vertx.core.http.HttpClient) CLI(io.vertx.core.cli.CLI) ShellService(io.vertx.ext.shell.ShellService) MalformedURLException(java.net.MalformedURLException) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Argument(io.vertx.core.cli.Argument) TelnetTermOptions(io.vertx.ext.shell.term.TelnetTermOptions) Command(io.vertx.ext.shell.command.Command) ShellServiceOptions(io.vertx.ext.shell.ShellServiceOptions) HttpClient(io.vertx.core.http.HttpClient) URL(java.net.URL)

Example 54 with HttpClient

use of io.vertx.core.http.HttpClient in project gravitee-management-rest-api by gravitee-io.

the class HttpProvider method get.

@Override
public CompletableFuture<Collection<DynamicProperty>> get() {
    CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx);
    URI requestUri = URI.create(dpConfiguration.getUrl());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());
    final HttpClientOptions options = new HttpClientOptions().setSsl(ssl).setTrustAll(true).setMaxPoolSize(1).setKeepAlive(false).setTcpKeepAlive(false).setConnectTimeout(2000);
    final HttpClient httpClient = vertx.createHttpClient(options);
    final int port = requestUri.getPort() != -1 ? requestUri.getPort() : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80);
    try {
        HttpClientRequest request = httpClient.request(HttpMethod.GET, port, requestUri.getHost(), requestUri.toString());
        request.handler(response -> {
            if (response.statusCode() == HttpStatusCode.OK_200) {
                response.bodyHandler(buffer -> {
                    future.complete(buffer);
                    // Close client
                    httpClient.close();
                });
            } else {
                future.complete(null);
            }
        });
        request.exceptionHandler(event -> {
            try {
                future.completeExceptionally(event);
                // Close client
                httpClient.close();
            } catch (IllegalStateException ise) {
            // Do not take care about exception when closing client
            }
        });
        request.end();
    } catch (Exception ex) {
        logger.error("Unable to look for dynamic properties", ex);
        future.completeExceptionally(ex);
    }
    return future.thenApply(buffer -> {
        if (buffer == null) {
            return null;
        }
        return mapper.map(buffer.toString());
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) VertxCompletableFuture(io.gravitee.management.services.dynamicproperties.provider.http.vertx.VertxCompletableFuture) URI(java.net.URI) HttpClientOptions(io.vertx.core.http.HttpClientOptions)

Example 55 with HttpClient

use of io.vertx.core.http.HttpClient in project vertx-web by vert-x3.

the class StaticHandlerTest method testNoHttp2Push.

@Test
public void testNoHttp2Push() throws Exception {
    stat.setWebRoot("webroot/somedir3");
    router.route().handler(stat);
    HttpServer http2Server = vertx.createHttpServer(new HttpServerOptions().setUseAlpn(true).setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert.pem")));
    http2Server.requestHandler(router).listen(8443);
    HttpClientOptions options = new HttpClientOptions().setSsl(true).setUseAlpn(true).setProtocolVersion(HttpVersion.HTTP_2).setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server-cert.pem"));
    HttpClient client = vertx.createHttpClient(options);
    HttpClientRequest request = client.get(8443, "localhost", "/testLinkPreload.html", resp -> {
        assertEquals(200, resp.statusCode());
        assertEquals(HttpVersion.HTTP_2, resp.version());
        resp.bodyHandler(this::assertNotNull);
        testComplete();
    });
    request.pushHandler(pushedReq -> pushedReq.handler(pushedResp -> {
        fail();
    }));
    request.end();
    await();
}
Also used : Arrays(java.util.Arrays) Date(java.util.Date) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Utils(io.vertx.ext.web.impl.Utils) HttpVersion(io.vertx.core.http.HttpVersion) PemKeyCertOptions(io.vertx.core.net.PemKeyCertOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) PemTrustOptions(io.vertx.core.net.PemTrustOptions) WebTestBase(io.vertx.ext.web.WebTestBase) DateFormat(java.text.DateFormat) Set(java.util.Set) Test(org.junit.Test) File(java.io.File) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Http2PushMapping(io.vertx.ext.web.Http2PushMapping) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClient(io.vertx.core.http.HttpClient) HttpClientRequest(io.vertx.core.http.HttpClientRequest) PemKeyCertOptions(io.vertx.core.net.PemKeyCertOptions) HttpClient(io.vertx.core.http.HttpClient) HttpServer(io.vertx.core.http.HttpServer) HttpServerOptions(io.vertx.core.http.HttpServerOptions) PemTrustOptions(io.vertx.core.net.PemTrustOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Test(org.junit.Test)

Aggregations

HttpClient (io.vertx.core.http.HttpClient)77 Test (org.junit.Test)47 HttpClientRequest (io.vertx.core.http.HttpClientRequest)36 HttpClientOptions (io.vertx.core.http.HttpClientOptions)25 Vertx (io.vertx.core.Vertx)22 HttpMethod (io.vertx.core.http.HttpMethod)22 JsonObject (io.vertx.core.json.JsonObject)22 Handler (io.vertx.core.Handler)18 Buffer (io.vertx.core.buffer.Buffer)18 HttpClientResponse (io.vertx.core.http.HttpClientResponse)16 TimeUnit (java.util.concurrent.TimeUnit)16 HttpServer (io.vertx.core.http.HttpServer)15 Async (io.vertx.ext.unit.Async)15 Before (org.junit.Before)15 File (java.io.File)14 CountDownLatch (java.util.concurrent.CountDownLatch)14 URL (java.net.URL)12 HttpServerOptions (io.vertx.core.http.HttpServerOptions)11 IOException (java.io.IOException)10 List (java.util.List)10