io.vertx.reactivex.ext.web.client.WebClient类的使用及代码示例

x33g5p2x  于2022-02-03 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(192)

本文整理了Java中io.vertx.reactivex.ext.web.client.WebClient类的一些代码示例,展示了WebClient类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WebClient类的具体详情如下:
包路径:io.vertx.reactivex.ext.web.client.WebClient
类名称:WebClient

WebClient介绍

暂无

代码示例

代码示例来源:origin: vert-x3/vertx-examples

@Override
 public void start() throws Exception {
  WebClient client = WebClient.create(vertx);
  client.get(80, "perdu.com", "/")
   .rxSend()
   .map(HttpResponse::bodyAsString)
   .subscribe(
    s -> LOGGER.info("From web client: " + s),
    Throwable::printStackTrace
   );
 }
}

代码示例来源:origin: FroMage/redpipe

private Single<String> get(Vertx vertx, URI uri){
  WebClient client = WebClient.create(vertx);
  Single<HttpResponse<Buffer>> responseHandler = 
      client.get(uri.getPort(), uri.getHost(), uri.getPath()).rxSend();
  return responseHandler.map(response -> response.body().toString())
      .doAfterTerminate(() -> client.close());
}

代码示例来源:origin: nemtech/nem2-sdk-java

Http(String host, NetworkHttp networkHttp) throws MalformedURLException {
  this.url = new URL(host);
  final Vertx vertx = Vertx.vertx();
  this.client = WebClient.create(vertx);
  objectMapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, true);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  this.networkHttp = networkHttp;
}

代码示例来源:origin: FroMage/redpipe

return fiber(() -> {
  WebClient webClient = WebClient.create(vertx, new WebClientOptions()
      .setSsl(true)
      .setUserAgent("vert-x3"));
      .put("client_secret", clientSecret)
      .put("code", code);
  HttpResponse<JsonObject> response = await(webClient.post(443, "github.com", "/login/oauth/access_token") 
      .putHeader("Accept", "application/json") 
      .putHeader("Content-Type", "application/json")

代码示例来源:origin: com.cv4j.netdiscovery/netdiscovery-core

webClient = WebClient.create(vertx, options);
    httpRequest = webClient.getAbs(request.getUrl());
    httpRequest = webClient.get(443,request.getUrlParser().getHost(),Preconditions.isNotBlank(request.getUrlParser().getQuery())?request.getUrlParser().getPath()+"?"+request.getUrlParser().getQuery():request.getUrlParser().getPath()).ssl(true);
    httpRequest = webClient.postAbs(request.getUrl());
    httpRequest = webClient.post(443,request.getUrlParser().getHost(),Preconditions.isNotBlank(request.getUrlParser().getQuery())?request.getUrlParser().getPath()+"?"+request.getUrlParser().getQuery():request.getUrlParser().getPath()).ssl(true);

代码示例来源:origin: FroMage/redpipe

WebClient webClient = WebClient.create(vertx, new WebClientOptions()
    .setSsl(true)
    .setUserAgent("vert-x3"));
HttpResponse<JsonObject> response = await(webClient.post(443, "api.github.com", "/gists") 
    .putHeader("Accept", "application/vnd.github.v3+json") 
    .putHeader("Content-Type", "application/json")
    .as(BodyCodec.jsonObject())
    .rxSendJsonObject(gistPayload));
webClient.close();

代码示例来源:origin: Cognifide/knotx

@Test
@KnotxApplyConfiguration("io/knotx/server/test-server-csrf.json")
public void whenDoPostSecureWithCSRF_expectOK(
  VertxTestContext context, Vertx vertx) {
 createPassThroughKnot(vertx, "test-splitter");
 createPassThroughKnot(vertx, "test-assembler");
 createSimpleKnot(vertx, "some-knot", "test", null);
 MultiMap body = MultiMap.caseInsensitiveMultiMap().add("field", "value");
 WebClient client = WebClient.create(vertx);
 client.get(KNOTX_SERVER_PORT, KNOTX_SERVER_ADDRESS, "/content/local/simple.html").send(
   ar -> {
    if (ar.succeeded()) {
     String token = getToken(ar.result().cookies());
     client.post(KNOTX_SERVER_PORT, KNOTX_SERVER_ADDRESS, "/content/local/simple.html")
       .putHeader(CSRFHandler.DEFAULT_HEADER_NAME, token)
       .putHeader(HttpHeaderNames.COOKIE.toString(),
         CSRFHandler.DEFAULT_COOKIE_NAME + "=" + token)
       .sendForm(body, res -> {
        if (res.succeeded()) {
         assertEquals(HttpResponseStatus.OK.code(), res.result().statusCode());
         context.completeNow();
        } else {
         context.failNow(ar.cause());
        }
       });
    } else {
     context.failNow(ar.cause());
    }
   });
}

代码示例来源:origin: nemtech/nem2-sdk-java

public Observable<NetworkType> getNetworkType() {
    return this.client
        .getAbs(this.url.toString())
        .as(BodyCodec.jsonObject())
        .rxSend()
        .toObservable()
        .map(Http::mapJsonObjectOrError)
        .map(json -> json.getString("name"))
        .map(name -> {
          if (name.equalsIgnoreCase("mijinTest"))
            return NetworkType.MIJIN_TEST;
          else {
            throw new IllegalArgumentException("network " + name + " is not supported yet by the sdk");
          }
        });
  }
}

代码示例来源:origin: io.gravitee.elasticsearch/gravitee-common-elasticsearch

this.httpClient = WebClient.create(vertx, options);
((WebClientInternal) this.httpClient.getDelegate()).addInterceptor(new Handler<HttpContext>() {
  @Override
  public void handle(HttpContext context) {

代码示例来源:origin: io.vertx/vertx-rx-java2

@Test
 public void testErrorHandling() throws Exception {
  try {
   client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
   Single<HttpResponse<WineAndCheese>> single = client
       .get(-1, "localhost", "/the_uri")
       .as(BodyCodec.json(WineAndCheese.class))
       .rxSend();
   single.subscribe(resp -> fail(), error -> {
    assertEquals(IllegalArgumentException.class, error.getClass());
    testComplete();
   });
   await();
  } catch (Throwable t) {
   fail();
  }
 }
}

代码示例来源:origin: nemtech/nem2-sdk-java

@Override
public Observable<List<Transaction>> getTransactions(List<String> transactionHashes) {
  JsonObject requestBody = new JsonObject();
  requestBody.put("transactionIds", transactionHashes);
  return this.client
      .postAbs(this.url.toString())
      .as(BodyCodec.jsonArray())
      .rxSendJson(requestBody)
      .toObservable()
      .map(Http::mapJsonArrayOrError)
      .map(json -> new JsonArray(json.toString()).stream().map(s -> (JsonObject) s).collect(Collectors.toList()))
      .flatMapIterable(item -> item)
      .map(new TransactionMapping())
      .toList()
      .toObservable();
}

代码示例来源:origin: io.gravitee.elasticsearch/gravitee-common-elasticsearch

/**
 * Perform an HTTP search query
 * @param indexes indexes names. If null search on all indexes
 * @param type document type separated by comma. If null search on all types
 * @param query json body query
 * @return elasticsearch response
 */
public Single<SearchResponse> search(final String indexes, final String type, final String query) {
  // index can be null _search on all index
  final StringBuilder url = new StringBuilder()
      .append('/')
      .append(indexes);
  if (type != null) {
    url.append('/').append(type);
  }
  url.append(URL_SEARCH);
  return httpClient
      .post(url.toString())
      .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
      .rxSendBuffer(Buffer.buffer(query))
      .map(response -> {
        if (response.statusCode() != HttpStatusCode.OK_200) {
          logger.error("Unable to search: url[{}] status[{}] query[{}] response[{}]",
              url.toString(), response.statusCode(), query, response.body());
          throw new ElasticsearchException("Unable to search");
        }
        return mapper.readValue(response.bodyAsString(), SearchResponse.class);
      });
}

代码示例来源:origin: io.gravitee.elasticsearch/gravitee-common-elasticsearch

@Override
public Single<Integer> getVersion() throws ElasticsearchException {
  return httpClient
      .get(URL_ROOT)
      .rxSend()
      .doOnError(throwable -> logger.error("Unable to get a connection to Elasticsearch", throwable))
      .map(response -> mapper.readTree(response.bodyAsString()).path("version").path("number").asText())
      .map(sVersion -> {
        float result = Float.valueOf(sVersion.substring(0, 3));
        int version = Integer.valueOf(sVersion.substring(0, 1));
        if (result < 2) {
          logger.warn("Please upgrade to Elasticsearch 2 or later. version={}", version);
        }
        return version;
      });
}

代码示例来源:origin: io.vertx/vertx-rx-java2

@Test
public void testPost() {
 int times = 5;
 waitFor(times);
 HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
 server.requestStream().handler(req -> req.bodyHandler(buff -> {
  assertEquals("onetwothree", buff.toString());
  req.response().end();
 }));
 try {
  server.listen(ar -> {
   client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
   Observable<Buffer> stream = Observable.just(Buffer.buffer("one"), Buffer.buffer("two"), Buffer.buffer("three"));
   Single<HttpResponse<Buffer>> single = client
       .post(8080, "localhost", "/the_uri")
       .rxSendStream(stream);
   for (int i = 0; i < times; i++) {
    single.subscribe(resp -> complete(), this::fail);
   }
  });
  await();
 } finally {
  server.close();
 }
}

代码示例来源:origin: com.cv4j.netdiscovery/netdiscovery-core

public void close() {

    if (webClient!=null) {
      webClient.close();
    }
  }
}

代码示例来源:origin: FroMage/redpipe

@Path("7error")
@GET
public CompletionStage<String> hello7Error(@Context Vertx vertx){
  io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx);
  System.err.println("Creating client");
  WebClientOptions options = new WebClientOptions();
  options.setSsl(true);
  options.setTrustAll(true);
  options.setVerifyHost(false);
  WebClient client = WebClient.create(rxVertx, options);
  Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
      "www.google.com", 
      "/robots.txt").rxSend();
  CompletableFuture<String> ret = new CompletableFuture<>();
  responseHandler
    .doAfterTerminate(() -> client.close())
    .subscribe(body -> {
    System.err.println("Got body");
    
    ret.completeExceptionally(new MyException());
  });
  System.err.println("Created client");
  return ret;
}

代码示例来源:origin: io.knotx/knotx-example-action-adapter-http

private WebClient getWebClient(Vertx vertx, HttpAdapterConfiguration configuration) {
 JsonObject clientOptions = configuration.getClientOptions();
 return clientOptions.isEmpty() ? WebClient.create(vertx) :
   WebClient.create(vertx, new WebClientOptions(clientOptions));
}

代码示例来源:origin: FroMage/redpipe

return fiber(() -> {
  WebClient webClient = WebClient.create(vertx, new WebClientOptions()
      .setSsl(true)
      .setUserAgent("vert-x3"));
      .put("client_secret", clientSecret)
      .put("code", code);
  HttpResponse<JsonObject> response = await(webClient.post(443, "github.com", "/login/oauth/access_token") 
      .putHeader("Accept", "application/json") 
      .putHeader("Content-Type", "application/json")

代码示例来源:origin: FroMage/redpipe

});
WebClient webClient = WebClient.create(vertx, new WebClientOptions()
    .setSsl(true)
    .setUserAgent("vert-x3"));
HttpResponse<JsonObject> response = await(webClient.post(443, "api.github.com", "/gists") 
    .putHeader("Accept", "application/vnd.github.v3+json") 
    .putHeader("Content-Type", "application/json")
    .as(BodyCodec.jsonObject())
    .rxSendJsonObject(gistPayload));
webClient.close();

代码示例来源:origin: nemtech/nem2-sdk-java

@Override
public Observable<Transaction> getTransaction(String transactionHash) {
  return this.client
      .getAbs(this.url + transactionHash)
      .as(BodyCodec.jsonObject())
      .rxSend()
      .toObservable()
      .map(Http::mapJsonObjectOrError)
      .map(json -> new JsonObject(json.toString()))
      .map(new TransactionMapping());
}

相关文章