@Override public void start() throws Exception { String filename = "upload.txt"; FileSystem fs = vertx.fileSystem(); WebClient client = WebClient.create(vertx); fs.props(filename, ares -> { FileProps props = ares.result(); System.out.println("props is " + props); long size = props.size(); HttpRequest<Buffer> req = client.put(8080, "localhost", "/"); req.putHeader("content-length", "" + size); fs.open(filename, new OpenOptions(), ares2 -> { req.sendStream(ares2.result(), 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); 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(); } }); } }
.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()) {
/** * Configure the request to add a new HTTP header. * @param name the header name * @param value the header value * @return a reference to this, so the API can be used fluently */ public io.vertx.rxjava.ext.web.client.HttpRequest<T> putHeader(String name, String value) { delegate.putHeader(name, value); return this; }
/** * Configure the request to add a new HTTP header. * @param name the header name * @param value the header value * @return a reference to this, so the API can be used fluently */ public io.vertx.rxjava.ext.web.client.HttpRequest<T> putHeader(String name, String value) { delegate.putHeader(name, value); return this; }
@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(); } });
/** * 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); } }
query.entrySet().forEach(e -> rq.addQueryParam(e.getKey(), e.getValue())); if (aclToken != null) { rq.putHeader(TOKEN_HEADER, aclToken);
private Future<JsonArray> retrieveServices(String token) { Future<JsonArray> future = Future.future(); String path = "/api/v1/namespaces/" + namespace + "/services"; client.get(path) .putHeader("Authorization", "Bearer " + token) .send(resp -> { if (resp.failed()) { future.fail(resp.cause()); } else if (resp.result().statusCode() != 200) { future.fail("Unable to retrieve services from namespace " + namespace + ", status code: " + resp.result().statusCode() + ", content: " + resp.result().bodyAsString()); } else { HttpResponse<Buffer> response = resp.result(); JsonArray items = response.bodyAsJsonObject().getJsonArray("items"); if (items == null) { future.fail("Unable to retrieve services from namespace " + namespace + " - no items"); } else { future.complete(items); watch(client, token, response.bodyAsJsonObject().getJsonObject("metadata").getString("resourceVersion")); } } }); return future; }
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()); }
/** * 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()); } }); }
/** * 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()); }); }
/** * Reads a secret from `path`. * * @param path the path * @param responseHandler the callback invoked with the result */ public void read(String path, Handler<AsyncResult<Secret>> responseHandler) { Objects.requireNonNull(responseHandler); client.get("/v1/" + Objects.requireNonNull(path)) .putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "No token to access the vault")) .send(response -> { if (response.failed()) { responseHandler.handle(VaultException.toFailure("Unable to access the Vault", response.cause())); return; } HttpResponse<Buffer> result = response.result(); if (result.statusCode() != 200) { responseHandler.handle(VaultException.toFailure(result.statusMessage(), result.statusCode(), result.bodyAsString())); } else { Secret secret = result.bodyAsJson(Secret.class); responseHandler.handle(Future.succeededFuture(secret)); } }); }
/** * Write a secret to `path`. * * @param path the path * @param resultHandler the callback invoked with the result */ public void write(String path, JsonObject secrets, Handler<AsyncResult<Secret>> resultHandler) { Objects.requireNonNull(resultHandler); client.post("/v1/" + Objects.requireNonNull(path)) .putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must be set")) .sendJsonObject(Objects.requireNonNull(secrets, "The secret must be set"), ar -> { if (ar.failed()) { resultHandler.handle(VaultException.toFailure("Unable to access the Vault", ar.cause())); return; } HttpResponse<Buffer> response = ar.result(); if (response.statusCode() == 200 || response.statusCode() == 204) { resultHandler.handle(Future.succeededFuture(response.bodyAsJson(Secret.class))); } else { resultHandler.handle(VaultException.toFailure(response.statusMessage(), response.statusCode(), response.bodyAsString())); } }); }
/** * get address space by address space name vie rest api * * @param name name of address space * @return * @throws InterruptedException */ public JsonObject getAddressSpace(String name, int expectedCode) throws Exception { String path = addressSpacesPath + "/" + name; log.info("GET-address-space: path '{}'", path); CompletableFuture<JsonObject> responsePromise = new CompletableFuture<>(); return doRequestNTimes(initRetry, () -> { client.get(endpoint.getPort(), endpoint.getHost(), path) .as(BodyCodec.jsonObject()) .putHeader(HttpHeaders.AUTHORIZATION.toString(), authzString) .send(ar -> responseHandler(ar, responsePromise, expectedCode, String.format("Error: get address space %s", name))); return responsePromise.get(30, TimeUnit.SECONDS); }, Optional.of(() -> kubernetes.getRestEndpoint()), Optional.empty()); }
/** * Looks up for the current token metadata. * * @param resultHandler the callback invoked with the result */ public void lookupSelf(Handler<AsyncResult<Lookup>> resultHandler) { client.get("/v1/auth/token/lookup-self") .putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must not be null")) .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() != 200) { resultHandler.handle(VaultException.toFailure(response.statusMessage(), response.statusCode(), response.bodyAsString())); } else { JsonObject object = response.bodyAsJsonObject(); Lookup lookup = object.getJsonObject("data").mapTo(Lookup.class); resultHandler.handle(Future.succeededFuture(lookup)); } }); }
@Test public void testUserAgentHeaderOverride() throws Exception { testRequest(client -> client.get("somehost", "somepath").putHeader(HttpHeaders.USER_AGENT.toString(), "smith"), req -> assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT))); }
@Test public void testFormMultipart() throws Exception { server.requestHandler(req -> { req.setExpectMultipart(true); req.endHandler(v -> { assertEquals("param1_value", req.getFormAttribute("param1")); req.response().end(); }); }); startServer(); MultiMap form = MultiMap.caseInsensitiveMultiMap(); form.add("param1", "param1_value"); HttpRequest<Buffer> builder = client.post("/somepath"); builder.putHeader("content-type", "multipart/form-data"); builder.sendForm(form, onSuccess(resp -> complete())); await(); }
req.putHeader(headerPrefix + i, String.valueOf(i));
startServer(); HttpRequest<Buffer> builder = client.get("/redirect") .putHeader("foo", "bar"); if (set != null) { builder = builder.followRedirects(set);