@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); client.get(8080, "localhost", "/") .as(BodyCodec.json(User.class)) .send(ar -> { if (ar.succeeded()) { HttpResponse<User> response = ar.result(); System.out.println("Got HTTP response body"); User user = response.body(); System.out.println("FirstName " + user.firstName); System.out.println("LastName " + user.lastName); System.out.println("Male " + user.male); } else { ar.cause().printStackTrace(); } }); } }
.as(BodyCodec.jsonObject()) .addQueryParam("grant_type", "client_credentials") .putHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") .putHeader("Authorization", authHeader) .send(authHandler -> { .as(BodyCodec.jsonObject()) .addQueryParam("q", queryToSearch) .putHeader("Authorization", header) .send(handler -> { if (handler.succeeded() && 200 == handler.result().statusCode()) { System.out.println(handler.result().body());
@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); Buffer body = Buffer.buffer("Hello World"); client.put(8080, "localhost", "/").sendBuffer(body, ar -> { if (ar.succeeded()) { HttpResponse<Buffer> response = ar.result(); System.out.println("Got HTTP response with status " + response.statusCode()); } else { ar.cause().printStackTrace(); } }); } }
@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); client.get(8080, "localhost", "/") .addQueryParam("firstName", "Dale") .addQueryParam("lastName", "Cooper") .addQueryParam("male", "true") .send(ar -> { if (ar.succeeded()) { HttpResponse<Buffer> response = ar.result(); System.out.println("Got HTTP response with status " + response.statusCode()); } else { ar.cause().printStackTrace(); } }); } }
/** * Deletes a secret from `path`. * * @param path the path * @param resultHandler the callback invoked with the result */ public void delete(String path, Handler<AsyncResult<Void>> resultHandler) { Objects.requireNonNull(resultHandler); client.delete("/v1/" + Objects.requireNonNull(path)) .putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must be set")) .send(ar -> { if (ar.failed()) { resultHandler.handle(VaultException.toFailure("Unable to access the Vault", ar.cause())); return; } HttpResponse<Buffer> response = ar.result(); if (response.statusCode() != 204) { resultHandler.handle(VaultException.toFailure(response.statusMessage(), response.statusCode(), response.bodyAsString())); } else { resultHandler.handle(Future.succeededFuture()); } }); }
@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); client.get(8080, "localhost", "/").send(ar -> { if (ar.succeeded()) { HttpResponse<Buffer> response = ar.result(); System.out.println("Got HTTP response with status " + response.statusCode() + " with data " + response.body().toString("ISO-8859-1")); } else { ar.cause().printStackTrace(); } }); } }
protected JsonObject getResource(String type, String basePath, String name, int expectedCode) throws Exception { String path = basePath + "/" + name; log.info("GET: path {}", path); CompletableFuture<JsonObject> responsePromise = new CompletableFuture<>(); return doRequestNTimes(initRetry, () -> { client.get(endpoint.getPort(), endpoint.getHost(), path) .as(BodyCodec.jsonObject()) .putHeader(HttpHeaders.AUTHORIZATION, authzString) .send(ar -> responseHandler(ar, responsePromise, expectedCode, String.format("Error: get %s %s", type, name))); return responsePromise.get(30, TimeUnit.SECONDS); }, Optional.of(endpointSupplier), Optional.empty()); }
private void getNow(RoutingContext ctx) { count++; final WebClient client = WebClient.create(vertx); client.get(80, HTTP_NOW, "/") .timeout(5000) .as(BodyCodec.jsonObject()) .send(ar -> { if (ar.succeeded()) { HttpResponse<JsonObject> response = ar.result(); JsonObject body = response.body(); String now = body.getJsonObject("now").getString("rfc2822"); ctx.response().end(now + " " + String.format(RESPONSE_STRING_FORMAT, HOSTNAME, count)); } else { ctx.response().setStatusCode(503).end(ar.cause().getMessage()); } }); }
Handler<AsyncResult<HttpResponse<Buffer>>> handler = ar -> { async.countDown(); }; HttpRequest<Buffer> req = client.post("/"); req.send(handler); req.sendBuffer(Buffer.buffer(), handler); req.sendForm(new CaseInsensitiveHeaders().add("a", "b"), handler); req.sendJson("", handler); req.sendJsonObject(new JsonObject(), handler); req.sendMultipartForm(MultipartForm.create().attribute("a", "b"), handler); req.sendStream(asyncFile, handler);
@Test public void testTimeout() throws Exception { AtomicInteger count = new AtomicInteger(); server.requestHandler(req -> count.incrementAndGet()); startServer(); HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath"); get.timeout(50).send(onFailure(err -> { assertTrue(err instanceof TimeoutException); testComplete(); })); await(); }
/** * Stop messaging client and get all informations about them (stdOut, stdErr, code, isRunning) * * @param uuid client id * @return * @throws InterruptedException * @throws ExecutionException * @throws TimeoutException */ public JsonObject stopClient(String uuid) throws InterruptedException, ExecutionException, TimeoutException { CompletableFuture<JsonObject> responsePromise = new CompletableFuture<>(); JsonObject request = new JsonObject(); request.put("id", uuid); client.delete(endpoint.getPort(), endpoint.getHost(), "") .as(BodyCodec.jsonObject()) .timeout(120000) .sendJson(request, ar -> responseHandler(ar, responsePromise, HttpURLConnection.HTTP_OK, "Error removing messaging clients")); return responsePromise.get(150000, TimeUnit.SECONDS); }
headers.forEach((item) -> request.putHeader(item.getKey(), item.getValue())); request.timeout(30000); body = Buffer.buffer(); request.sendBuffer(body, InOut.replyWeb(this.getClass(), context, consumer));
.putHeader(headerName, headerValue) .addQueryParam("c", "X"); req.send(ar -> { context.assertTrue(ar.succeeded()); context.assertEquals(200, ar.result().statusCode()); req.queryParams().clear(); Async async = context.async(); req.send(ar -> { context.assertTrue(ar.succeeded()); context.assertEquals(200, ar.result().statusCode());
query.entrySet().forEach(e -> rq.addQueryParam(e.getKey(), e.getValue())); if (aclToken != null) { rq.putHeader(TOKEN_HEADER, aclToken); rq.timeout(timeoutMs); rq.sendBuffer(body == null ? Buffer.buffer() : Buffer.buffer(body), h -> { if (h.succeeded()) { HttpResponse<Buffer> resp = h.result();
/** * Renews the current token. * * @param leaseDurationInSecond the extension in second * @param resultHandler the callback invoked with the result */ public void renewSelf(long leaseDurationInSecond, Handler<AsyncResult<Auth>> resultHandler) { JsonObject payload = null; if (leaseDurationInSecond > 0) { payload = new JsonObject().put("increment", leaseDurationInSecond); } HttpRequest<Buffer> request = client.post("/v1/auth/token/renew-self") .putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must not be null")); Handler<AsyncResult<HttpResponse<Buffer>>> handler = ar -> { if (ar.failed()) { resultHandler.handle(VaultException.toFailure("Unable to access the Vault", ar.cause())); return; } manageAuthResult(resultHandler, ar.result()); }; if (payload != null) { request.sendJsonObject(payload, handler); } else { request.send(handler); } }
startServer(); HttpRequest<Buffer> builder = client.get("/redirect") .putHeader("foo", "bar"); if (set != null) { builder = builder.followRedirects(set); builder.send(onSuccess(resp -> { if (expect) { assertEquals(200, resp.statusCode());
@Test public void testMutateRequestInterceptor() throws Exception { server.requestHandler(req -> req.response().end()); startServer(); client.addInterceptor(this::handleMutateRequest); HttpRequest<Buffer> builder = client.get("/somepath").host("another-host").port(8081); builder.send(onSuccess(resp -> complete())); await(); }
@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); MultiMap form = MultiMap.caseInsensitiveMultiMap(); form.add("firstName", "Dale"); form.add("lastName", "Cooper"); form.add("male", "true"); client .post(8080, "localhost", "/") .putHeader("content-type", "multipart/form-data") .sendForm(form, ar -> { if (ar.succeeded()) { HttpResponse<Buffer> response = ar.result(); System.out.println("Got HTTP response with status " + response.statusCode()); } else { ar.cause().printStackTrace(); } }); } }
/** * Creates a new token. * * @param tokenRequest the token request * @param resultHandler the callback invoked with the result. */ public void createToken(TokenRequest tokenRequest, Handler<AsyncResult<Auth>> resultHandler) { client.post("/v1/auth/token/create" + ((tokenRequest.getRole() == null) ? "" : "/" + tokenRequest.getRole())) .putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must be set")) .sendJsonObject(tokenRequest.toPayload(), ar -> { if (ar.failed()) { resultHandler.handle(VaultException.toFailure("Unable to access the Vault", ar.cause())); return; } manageAuthResult(resultHandler, ar.result()); }); }
@Override public void handle(HttpContext context) { context.request() .timeout(configuration.getRequestTimeout()) .putHeader(HttpHeaders.ACCEPT, CONTENT_TYPE) .putHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // Basic authentication if (authorizationHeader != null) { context.request().putHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); } context.next(); } });