本文整理汇总了Java中org.asynchttpclient.AsyncHttpClient类的典型用法代码示例。如果您正苦于以下问题:Java AsyncHttpClient类的具体用法?Java AsyncHttpClient怎么用?Java AsyncHttpClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AsyncHttpClient类属于org.asynchttpclient包,在下文中一共展示了AsyncHttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testMaxTotalConnections
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void testMaxTotalConnections() throws Exception {
try (AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setMaxConnections(1))) {
String url = getTargetUrl();
int i;
Exception exception = null;
for (i = 0; i < 3; i++) {
try {
logger.info("{} requesting url [{}]...", i, url);
Response response = client.prepareGet(url).execute().get();
logger.info("{} response [{}].", i, response);
} catch (Exception ex) {
exception = ex;
}
}
assertNull(exception);
}
}
示例2: testMaxTotalConnectionsException
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone", expectedExceptions = TooManyConnectionsException.class)
public void testMaxTotalConnectionsException() throws Throwable {
try (AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setMaxConnections(1))) {
String url = getTargetUrl();
List<ListenableFuture<Response>> futures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
logger.info("{} requesting url [{}]...", i, url);
futures.add(client.prepareGet(url).execute());
}
Exception exception = null;
for (ListenableFuture<Response> future : futures) {
try {
future.get();
} catch (Exception ex) {
exception = ex;
break;
}
}
assertNotNull(exception);
throw exception.getCause();
}
}
示例3: multipleMaxConnectionOpenTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone", expectedExceptions = TooManyConnectionsException.class)
public void multipleMaxConnectionOpenTest() throws Throwable {
try (AsyncHttpClient c = asyncHttpClient(config().setKeepAlive(true).setConnectTimeout(5000).setMaxConnections(1))) {
String body = "hello there";
// once
Response response = c.preparePost(getTargetUrl()).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
// twice
Exception exception = null;
try {
c.preparePost(String.format("http://localhost:%d/foo/test", port2)).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS);
fail("Should throw exception. Too many connections issued.");
} catch (Exception ex) {
ex.printStackTrace();
exception = ex;
}
assertNotNull(exception);
throw exception.getCause();
}
}
示例4: testPooledEventsFired
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void testPooledEventsFired() throws Exception {
RequestBuilder request = get("http://localhost:" + port1 + "/Test");
try (AsyncHttpClient client = asyncHttpClient()) {
EventCollectingHandler firstHandler = new EventCollectingHandler();
client.executeRequest(request, firstHandler).get(3, TimeUnit.SECONDS);
firstHandler.waitForCompletion(3, TimeUnit.SECONDS);
EventCollectingHandler secondHandler = new EventCollectingHandler();
client.executeRequest(request, secondHandler).get(3, TimeUnit.SECONDS);
secondHandler.waitForCompletion(3, TimeUnit.SECONDS);
Object[] expectedEvents = new Object[] { CONNECTION_POOL_EVENT, CONNECTION_POOLED_EVENT, REQUEST_SEND_EVENT, HEADERS_WRITTEN_EVENT, STATUS_RECEIVED_EVENT,
HEADERS_RECEIVED_EVENT, CONNECTION_OFFER_EVENT, COMPLETED_EVENT };
assertEquals(secondHandler.firedEvents.toArray(), expectedEvents, "Got " + Arrays.toString(secondHandler.firedEvents.toArray()));
}
}
示例5: negativeContentTypeTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void negativeContentTypeTest() throws Exception {
AsyncHttpClientConfig config = config()//
.setConnectTimeout(100)//
.setMaxConnections(50)//
.setRequestTimeout(5 * 60 * 1000) // 5 minutes
.build();
try (AsyncHttpClient client = asyncHttpClient(config)) {
RequestBuilder requestBuilder = post(getTargetUrl())//
.setHeader("Content-Type", "message/rfc822")//
.setBody(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes())));
Future<Response> future = client.executeRequest(requestBuilder.build());
System.out.println("waiting for response");
Response response = future.get();
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getResponseBody(), MY_MESSAGE);
}
}
示例6: testIgnoreProxyPropertiesByDefault
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
public void testIgnoreProxyPropertiesByDefault() throws IOException, ExecutionException, TimeoutException, InterruptedException {
// FIXME not threadsafe!
Properties originalProps = new Properties();
originalProps.putAll(System.getProperties());
System.setProperty(ProxyUtils.PROXY_HOST, "localhost");
System.setProperty(ProxyUtils.PROXY_PORT, String.valueOf(port1));
System.setProperty(ProxyUtils.PROXY_NONPROXYHOSTS, "localhost");
AsyncHttpClientConfigHelper.reloadProperties();
try (AsyncHttpClient client = asyncHttpClient()) {
String target = "http://localhost:1234/";
Future<Response> f = client.prepareGet(target).execute();
try {
f.get(3, TimeUnit.SECONDS);
fail("should not be able to connect");
} catch (ExecutionException e) {
// ok, no proxy used
}
} finally {
System.setProperties(originalProps);
}
}
示例7: testWildcardNonProxyHosts
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
public void testWildcardNonProxyHosts() throws IOException, ExecutionException, TimeoutException, InterruptedException {
// FIXME not threadsafe!
Properties originalProps = new Properties();
originalProps.putAll(System.getProperties());
System.setProperty(ProxyUtils.PROXY_HOST, "127.0.0.1");
System.setProperty(ProxyUtils.PROXY_PORT, String.valueOf(port1));
System.setProperty(ProxyUtils.PROXY_NONPROXYHOSTS, "127.*");
AsyncHttpClientConfigHelper.reloadProperties();
try (AsyncHttpClient client = asyncHttpClient(config().setUseProxyProperties(true))) {
String nonProxifiedTarget = "http://127.0.0.1:1234/";
Future<Response> f = client.prepareGet(nonProxifiedTarget).execute();
try {
f.get(3, TimeUnit.SECONDS);
fail("should not be able to connect");
} catch (ExecutionException e) {
// ok, no proxy used
}
} finally {
System.setProperties(originalProps);
}
}
示例8: deferredSimple
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void deferredSimple() throws IOException, ExecutionException, TimeoutException, InterruptedException {
try (AsyncHttpClient client = asyncHttpClient(getAsyncHttpClientConfig())) {
BoundRequestBuilder r = client.prepareGet("http://localhost:" + port1 + "/deferredSimple");
CountingOutputStream cos = new CountingOutputStream();
BodyDeferringAsyncHandler bdah = new BodyDeferringAsyncHandler(cos);
Future<Response> f = r.execute(bdah);
Response resp = bdah.getResponse();
assertNotNull(resp);
assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
assertEquals(resp.getHeader("content-length"), String.valueOf(HALF_GIG));
// we got headers only, it's probably not all yet here (we have BIG file
// downloading)
assertTrue(cos.getByteCount() <= HALF_GIG);
// now be polite and wait for body arrival too (otherwise we would be
// dropping the "line" on server)
f.get();
// it all should be here now
assertEquals(cos.getByteCount(), HALF_GIG);
}
}
示例9: propFindWebDavTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void propFindWebDavTest() throws InterruptedException, IOException, ExecutionException {
try (AsyncHttpClient c = asyncHttpClient()) {
Request mkcolRequest = new RequestBuilder("MKCOL").setUrl(getTargetUrl()).build();
Response response = c.executeRequest(mkcolRequest).get();
assertEquals(response.getStatusCode(), 201);
Request putRequest = put(String.format("http://localhost:%s/folder1/Test.txt", port1)).setBody("this is a test").build();
response = c.executeRequest(putRequest).get();
assertEquals(response.getStatusCode(), 201);
Request propFindRequest = new RequestBuilder("PROPFIND").setUrl(String.format("http://localhost:%s/folder1/Test.txt", port1)).build();
response = c.executeRequest(propFindRequest).get();
assertEquals(response.getStatusCode(), 207);
assertTrue(response.getResponseBody().contains("<status>HTTP/1.1 200 OK</status>"));
}
}
示例10: cancelStreamedResponseTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void cancelStreamedResponseTest() throws Throwable {
try (AsyncHttpClient c = asyncHttpClient()) {
// Cancel immediately
c.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new CancellingStreamedAsyncProvider(0)).get();
// Cancel after 1 element
c.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new CancellingStreamedAsyncProvider(1)).get();
// Cancel after 10 elements
c.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new CancellingStreamedAsyncProvider(10)).get();
// Make sure a regular request works
assertEquals(c.preparePost(getTargetUrl()).setBody("Hello").execute().get().getResponseBody(), "Hello");
}
}
示例11: basicResponseFilterTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void basicResponseFilterTest() throws Exception {
ResponseFilter responseFilter = new ResponseFilter() {
@Override
public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {
return ctx;
}
};
try (AsyncHttpClient c = asyncHttpClient(config().addResponseFilter(responseFilter))) {
Response response = c.preparePost(getTargetUrl()).execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
}
}
示例12: replayResponseFilterTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void replayResponseFilterTest() throws Exception {
final AtomicBoolean replay = new AtomicBoolean(true);
ResponseFilter responseFilter = new ResponseFilter() {
public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {
if (replay.getAndSet(false)) {
Request request = new RequestBuilder(ctx.getRequest()).addHeader("X-Replay", "true").build();
return new FilterContext.FilterContextBuilder<T>().asyncHandler(ctx.getAsyncHandler()).request(request).replayRequest(true).build();
}
return ctx;
}
};
try (AsyncHttpClient c = asyncHttpClient(config().addResponseFilter(responseFilter))) {
Response response = c.preparePost(getTargetUrl()).execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getHeader("X-Replay"), "true");
}
}
示例13: replayStatusCodeResponseFilterTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void replayStatusCodeResponseFilterTest() throws Exception {
final AtomicBoolean replay = new AtomicBoolean(true);
ResponseFilter responseFilter = new ResponseFilter() {
public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {
if (ctx.getResponseStatus() != null && ctx.getResponseStatus().getStatusCode() == 200 && replay.getAndSet(false)) {
Request request = new RequestBuilder(ctx.getRequest()).addHeader("X-Replay", "true").build();
return new FilterContext.FilterContextBuilder<T>().asyncHandler(ctx.getAsyncHandler()).request(request).replayRequest(true).build();
}
return ctx;
}
};
try (AsyncHttpClient c = asyncHttpClient(config().addResponseFilter(responseFilter))) {
Response response = c.preparePost(getTargetUrl()).execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getHeader("X-Replay"), "true");
}
}
示例14: replayHeaderResponseFilterTest
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(groups = "standalone")
public void replayHeaderResponseFilterTest() throws Exception {
final AtomicBoolean replay = new AtomicBoolean(true);
ResponseFilter responseFilter = new ResponseFilter() {
public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {
if (ctx.getResponseHeaders() != null && ctx.getResponseHeaders().getHeaders().get("Ping").equals("Pong") && replay.getAndSet(false)) {
Request request = new RequestBuilder(ctx.getRequest()).addHeader("Ping", "Pong").build();
return new FilterContext.FilterContextBuilder<T>().asyncHandler(ctx.getAsyncHandler()).request(request).replayRequest(true).build();
}
return ctx;
}
};
try (AsyncHttpClient c = asyncHttpClient(config().addResponseFilter(responseFilter))) {
Response response = c.preparePost(getTargetUrl()).addHeader("Ping", "Pong").execute().get();
assertNotNull(response);
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getHeader("Ping"), "Pong");
}
}
示例15: testReadingOkResponse
import org.asynchttpclient.AsyncHttpClient; //导入依赖的package包/类
@Test(timeOut = 5000L)
public void testReadingOkResponse() throws Exception {
PubSubMessage expected = new PubSubMessage("foo", "response");
CompletableFuture<Response> response = getOkFuture(getOkResponse(expected.asJSON()));
AsyncHttpClient mockClient = mockClientWith(response);
pubscriber.setClient(mockClient);
pubscriber.send(new PubSubMessage("foo", "bar"));
// This is async (but practically still very fast since we mocked the response), so need a timeout.
PubSubMessage actual = fetchAsync().get();
Assert.assertNotNull(actual);
Assert.assertEquals(actual.getId(), expected.getId());
Assert.assertEquals(actual.getContent(), expected.getContent());
}