io.vertx.core.http.HttpClient类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(14.6k)|赞(0)|评价(0)|浏览(178)

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

HttpClient介绍

[英]An asynchronous HTTP client.

It allows you to make requests to HTTP servers, and a single client can make requests to any server.

It also allows you to open WebSockets to servers.

The client can also pool HTTP connections.

For pooling to occur, keep-alive must be true on the io.vertx.core.http.HttpClientOptions (default is true). In this case connections will be pooled and re-used if there are pending HTTP requests waiting to get a connection, otherwise they will be closed.

This gives the benefits of keep alive when the client is loaded but means we don't keep connections hanging around unnecessarily when there would be no benefits anyway.

The client also supports pipe-lining of requests. Pipe-lining means another request is sent on the same connection before the response from the preceding one has returned. Pipe-lining is not appropriate for all requests.

To enable pipe-lining, it must be enabled on the io.vertx.core.http.HttpClientOptions (default is false).

When pipe-lining is enabled the connection will be automatically closed when all in-flight responses have returned and there are no outstanding pending requests to write.

The client is designed to be reused between requests.
[中]异步HTTP客户端。
它允许您向HTTP服务器发出请求,单个客户端可以向任何服务器发出请求。
它还允许您向服务器打开WebSocket。
客户机还可以共用HTTP连接。
要发生池,io上的keep alive必须为true。维特斯。果心http。HttpClientOptions(默认值为true)。在这种情况下,如果有挂起的HTTP请求等待获取连接,则连接将被池化并重新使用,否则它们将被关闭。
这提供了在客户端加载时保持活动的好处,但意味着我们不会在没有任何好处的情况下不必要地保持连接。
客户端还支持请求的管道内衬。管道内衬意味着在前一个请求的响应返回之前,在同一个连接上发送另一个请求。管道衬里并非适用于所有要求。
要启用管道内衬,必须在io上启用。维特斯。果心http。HttpClientOptions(默认值为false)。
启用管道内衬后,当所有飞行响应都已返回且没有未决的写入请求时,连接将自动关闭。
客户端被设计为在请求之间重用。

代码示例

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testPutHeaderReplacesPreviousHeaders() throws Exception {
 server.requestHandler(req ->
  req.response()
   .putHeader("Location", "http://example1.org")
   .putHeader("location", "http://example2.org")
   .end());
 server.listen(onSuccess(server -> {
  client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, onSuccess(resp -> {
   assertEquals(singletonList("http://example2.org"), resp.headers().getAll("LocatioN"));
   testComplete();
   })).end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testBeginPipelinedRequestByResponseSentBeforeRequestCompletion() throws Exception {
 server.requestHandler(req -> {
  if (req.method() == HttpMethod.POST) {
   req.pause();
   vertx.setTimer(100, id1 -> {
    req.response().end();
    vertx.setTimer(100, id2 -> {
     req.resume();
    });
   });
  } else if (req.method() == HttpMethod.GET) {
   req.response().end();
  }
 });
 startServer();
 client.close();
 client = vertx.createHttpClient(new HttpClientOptions().setPipelining(true).setMaxPoolSize(1).setKeepAlive(true));
 client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", resp -> {
 }).end(TestUtils.randomAlphaString(1024));
 client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", resp -> {
  testComplete();
 });
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testServerResponseWriteBufferFromOtherThread() throws Exception {
 server.requestHandler(req -> {
  runAsync(() -> {
   req.response().write("hello ").end("world");
  });
 }).listen(onSuccess(v -> {
  client.get(8080, "localhost", "/somepath", onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   resp.bodyHandler(buff -> {
    assertEquals(Buffer.buffer("hello world"), buff);
    testComplete();
   });
  })).exceptionHandler(this::fail).end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testHttpClientResponsePause(Handler<HttpClientResponse> h) throws Exception {
 server.requestHandler(req -> req.response().end("ok"));
 startServer();
 client.close();
 client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(1).setKeepAlive(true));
 client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, onSuccess(resp1 -> {
  h.handle(resp1);
  vertx.setTimer(10, timerId -> {
   // The connection should be resumed as it's ended
   client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, onSuccess(resp2 -> {
    assertSame(resp1.request().connection(), resp2.request().connection());
    resp2.endHandler(v -> testComplete());
   }));
  });
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testClientConnectionHandler(boolean local, boolean global) throws Exception {
 server.requestHandler(req -> {
  req.response().end();
 });
 CountDownLatch listenLatch = new CountDownLatch(1);
 server.listen(onSuccess(s -> listenLatch.countDown()));
 awaitLatch(listenLatch);
 AtomicInteger status = new AtomicInteger();
 Handler<HttpConnection> handler = conn -> status.getAndIncrement();
 if (global) {
  client.connectionHandler(handler);
 }
 HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
  assertEquals((local ? 1 : 0) + (global ? 1 : 0), status.getAndIncrement());
  testComplete();
 });
 if (local) {
  req.connectionHandler(handler);
 }
 req.end();
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testPerHostPooling() throws Exception {
 client.close();
 client = vertx.createHttpClient(new HttpClientOptions()
  .setMaxPoolSize(1)
  .setKeepAlive(true)
  .setPipelining(false));
 testPerXXXPooling((i, handler) -> client.get(DEFAULT_HTTP_PORT, "host" + i, "/somepath", handler).setHost("host:8080")
  .putHeader("key", "host" + i), req -> req.getHeader("key"));
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testServerActualPortWhenSet() {
 server
   .requestHandler(request -> {
    request.response().end("hello");
   })
   .listen(ar -> {
    assertEquals(ar.result().actualPort(), DEFAULT_HTTP_PORT);
    vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", onSuccess(response -> {
     assertEquals(response.statusCode(), 200);
     response.bodyHandler(body -> {
      assertEquals(body.toString("UTF-8"), "hello");
      testComplete();
     });
    }));
   });
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

Context ctx = contextFactory.apply(vertx);
ctx.runOnContext(v1 -> {
 HttpServer server = vertx.createHttpServer().requestHandler(req -> {
  HttpServerResponse response = req.response();
  response.setStatusCode(200).setChunked(true).write("bye").end();
  response.close();
 });
 server.listen(8080, "localhost", onSuccess(s -> {
  expectedThread.set(Thread.currentThread());
  expectedContext.set(Vertx.currentContext());
  latch.countDown();
 }));
});
awaitLatch(latch);
HttpClient client = vertx.createHttpClient();
client.put(8080, "localhost", "/", onSuccess(resp -> {
 resp.netSocket().closeHandler(v -> {
  vertx.close(v4 -> {
   assertTrue(requestBeginCalled.get());
  });
 });
})).exceptionHandler(err -> {
 fail(err.getMessage());
}).setChunked(true).write(Buffer.buffer("hello")).end();
await();

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testHttpSocksProxyRequest() throws Exception {
 startProxy(null, ProxyType.SOCKS5);
 client.close();
 client = vertx.createHttpClient(new HttpClientOptions()
   .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5).setHost("localhost").setPort(proxy.getPort())));
 server.requestHandler(req -> {
  req.response().end();
 });
 server.listen(onSuccess(s -> {
  client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   assertNotNull("request did not go through proxy", proxy.getLastUri());
   testComplete();
  })).exceptionHandler(th -> fail(th)).end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

ctx.runOnContext(v1 -> {
 expectedThread.set(Thread.currentThread());
 expectedContext.set(Vertx.currentContext());
 HttpClient client = vertx.createHttpClient();
 checker.accept(expectedThread.get(), expectedContext.get());
 HttpClientRequest req = client.put(8080, "localhost", "/");
 req.handler(resp -> {
  executeInVanillaThread(() -> {
   client.close();
   vertx.close(v2 -> {
    assertTrue(requestBeginCalled.get());
  });
 });
 req.setChunked(true).write("hello");
 req.end();
});

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testClientWebsocketWithHttp2Client() throws Exception {
 client.close();
 client = vertx.createHttpClient(new HttpClientOptions().setHttp2ClearTextUpgrade(false).setProtocolVersion(HttpVersion.HTTP_2));
 server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT));
 server.requestHandler(req -> {
  req.response().setChunked(true).write("connect");
 });
 server.websocketHandler(ws -> {
  ws.writeFinalTextFrame("ok");
 });
 server.listen(onSuccess(server -> {
  client.getNow(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", resp -> {
   client.websocket(DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/", ws -> {
    ws.handler(buff -> {
     assertEquals("ok", buff.toString());
     testComplete();
    });
   });
  });
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testSendFileFromClasspath() {
 vertx.createHttpServer(new HttpServerOptions().setPort(8080)).requestHandler(res -> {
  res.response().sendFile(webRoot + "/somefile.html");
 }).listen(onSuccess(res -> {
  vertx.createHttpClient(new HttpClientOptions()).request(HttpMethod.GET, 8080, "localhost", "/", onSuccess(resp -> {
   resp.bodyHandler(buff -> {
    assertTrue(buff.toString().startsWith("<html><body>blah</body></html>"));
    testComplete();
   });
  })).end();
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

private void testFollowRedirectWithBody(Function<Buffer, Buffer> translator) throws Exception {
 Buffer expected = TestUtils.randomBuffer(2048);
 AtomicBoolean redirected = new AtomicBoolean();
 server.requestHandler(req -> {
  if (redirected.compareAndSet(false, true)) {
   assertEquals(HttpMethod.PUT, req.method());
   req.bodyHandler(body -> {
    assertEquals(body, expected);
    String scheme = createBaseServerOptions().isSsl() ? "https" : "http";
    req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end();
   });
  } else {
   assertEquals(HttpMethod.GET, req.method());
   req.response().end();
  }
 });
 startServer();
 client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", onSuccess(resp -> {
  assertEquals(200, resp.statusCode());
  testComplete();
 })).setFollowRedirects(true).end(translator.apply(expected));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Override
public void start() throws Exception {
 assertTrue(Vertx.currentContext().isWorkerContext());
 assertTrue(Context.isOnWorkerThread());
 HttpServer server1 = vertx.createHttpServer(new HttpServerOptions()
     .setHost(HttpTestBase.DEFAULT_HTTP_HOST).setPort(HttpTestBase.DEFAULT_HTTP_PORT));
 server1.requestHandler(req -> {
  assertTrue(Vertx.currentContext().isWorkerContext());
  assertTrue(Context.isOnWorkerThread());
  Buffer buf = Buffer.buffer();
  req.handler(buf::appendBuffer);
  req.endHandler(v -> {
   assertEquals("hello", buf.toString());
   req.response().end("bye");
  });
 }).listen(onSuccess(s -> {
  client.put(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/blah", onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   resp.handler(buf -> {
    assertEquals("bye", buf.toString());
    resp.endHandler(v -> {
     testComplete();
    });
   });
  })).setChunked(true).write(Buffer.buffer("hello")).end();
 }));

代码示例来源:origin: eclipse-vertx/vert.x

req.endHandler(v -> {
   assertEquals(expected, body);
  });
startServer();
AtomicBoolean called = new AtomicBoolean();
HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", ar -> {
 assertEquals(expectFail, ar.failed());
 if (ar.succeeded()) {
  HttpClientResponse resp = ar.result();
  assertEquals(200, resp.statusCode());
  testComplete();
 } else {
}).setFollowRedirects(true)
 .setChunked(true)
 .write(buff1);
awaitLatch(latch);

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testFollowRedirectSendHeadThenBody() throws Exception {
 Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(2048));
 AtomicBoolean redirected = new AtomicBoolean();
 server.requestHandler(req -> {
  if (redirected.compareAndSet(false, true)) {
   assertEquals(HttpMethod.PUT, req.method());
   req.bodyHandler(body -> {
    assertEquals(body, expected);
    req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, "/whatever").end();
   });
  } else {
   assertEquals(HttpMethod.GET, req.method());
   req.response().end();
  }
 });
 startServer();
 HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", onSuccess(resp -> {
  assertEquals(200, resp.statusCode());
  testComplete();
 })).setFollowRedirects(true);
 req.putHeader("Content-Length", "" + expected.length());
 req.exceptionHandler(this::fail);
 req.sendHead(v -> {
  req.end(expected);
 });
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testHandleInvalid204Response() throws Exception {
 int numReq = 3;
 waitFor(numReq);
 client.close();
 client = vertx.createHttpClient(new HttpClientOptions().setPipelining(true).setKeepAlive(true).setMaxPoolSize(1));
 server.requestHandler(r -> {
  // Generate an invalid response for the pipe-lined
  r.response().setChunked(true).setStatusCode(204).end();
 }).listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, onSuccess(v1 -> {
  for (int i = 0;i < numReq;i++) {
   AtomicInteger count = new AtomicInteger();
   HttpClientRequest post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath",
    onSuccess(r -> {
     r.endHandler(v2 -> {
      complete();
     });
    })).exceptionHandler(err -> {
    if (count.incrementAndGet() == 1) {
     complete();
    }
   });
   post.end();
  }
 }));
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testPausedHttpServerRequestDuringLastChunkEndsTheRequest() throws Exception {
 server.requestHandler(req -> {
  req.handler(buff -> {
   assertEquals("small", buff.toString());
   req.pause();
  });
  req.endHandler(v -> {
   req.response().end();
  });
 });
 startServer();
 client.close();
 client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1));
 client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/someuri", resp -> {
  complete();
 }).end("small");
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testServerWebsocketIdleTimeout() {
 server.close();
 server = vertx.createHttpServer(new HttpServerOptions().setIdleTimeout(1).setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST));
 server.websocketHandler(ws -> {}).listen(ar -> {
  assertTrue(ar.succeeded());
  client.websocket(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", ws -> {
   ws.closeHandler(v -> testComplete());
  });
 });
 await();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testPutHeadersOnRequest() {
 server.requestHandler(req -> {
  assertEquals("bar", req.headers().get("foo"));
  assertEquals("bar", req.getHeader("foo"));
  req.response().end();
 });
 server.listen(onSuccess(server -> {
  client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, onSuccess(resp -> {
   assertEquals(200, resp.statusCode());
   testComplete();
  })).putHeader("foo", "bar").end();
 }));
 await();
}

相关文章