@Test public void urlWithoutSlashTest() throws Exception { try (AsyncHttpClient c = asyncHttpClient()) { String body = "hello there"; Response response = c.preparePost(String.format("http://localhost:%d/foo/test", port1)).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS); assertEquals(response.getResponseBody(), body); } } }
@Test(groups = "standalone") public void testQueryParameters() throws Exception { try (AsyncHttpClient client = asyncHttpClient()) { Future<Response> f = client.prepareGet("http://localhost:" + port1 + "/foo").addHeader("Accepts", "*/*").execute(); Response resp = f.get(3, TimeUnit.SECONDS); assertNotNull(resp); assertEquals(resp.getStatusCode(), 400); assertEquals(resp.getResponseBody(), BAD_REQUEST_STR); } }
@Test public void testMaxRetry() { try (AsyncHttpClient ahc = asyncHttpClient(config().setMaxRequestRetry(0))) { ahc.executeRequest(ahc.prepareGet(getTargetUrl()).build()).get(); fail(); } catch (Exception t) { assertEquals(t.getCause(), RemotelyClosedException.INSTANCE); } }
@Test public void postWithQueryString() throws IOException, ExecutionException, TimeoutException, InterruptedException { try (AsyncHttpClient client = asyncHttpClient()) { Future<Response> f = client.preparePost("http://localhost:" + port1 + "/?a=b").setBody("abc".getBytes()).execute(); Response resp = f.get(3, TimeUnit.SECONDS); assertNotNull(resp); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); } }
@Test public void testRequestNonProxyHost() throws IOException, ExecutionException, TimeoutException, InterruptedException { ProxyServer proxy = proxyServer("localhost", port1 - 1).setNonProxyHost("localhost").build(); try (AsyncHttpClient client = asyncHttpClient()) { String target = "http://localhost:" + port1 + "/"; Future<Response> f = client.prepareGet(target).setProxyServer(proxy).execute(); Response resp = f.get(3, TimeUnit.SECONDS); assertNotNull(resp); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); assertEquals(resp.getHeader("target"), "/"); } }
@Test(groups = "online", enabled = false) public void redirected302Test() throws Exception { isSet.getAndSet(false); try (AsyncHttpClient c = asyncHttpClient()) { Response response = c.prepareGet(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", "https://www.microsoft.com/").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); String anyMicrosoftPage = "https://www.microsoft.com[^:]*:443"; String baseUrl = getBaseUrl(response.getUri()); assertTrue(baseUrl.matches(anyMicrosoftPage), "response does not show redirection to " + anyMicrosoftPage); } }
@Test public void testPutImageFile() throws Exception { try (AsyncHttpClient client = asyncHttpClient(config().setRequestTimeout(100 * 6000))) { InputStream inputStream = new BufferedInputStream(new FileInputStream(LARGE_IMAGE_FILE)); Response response = client.preparePut(getTargetUrl()).addBodyPart(new InputStreamPart("test", inputStream, LARGE_IMAGE_FILE.getName(), LARGE_IMAGE_FILE.length(), "application/octet-stream", UTF_8)).execute().get(); assertEquals(response.getStatusCode(), 200); } }
@Test public void testEmptyBody() throws IOException { try (AsyncHttpClient ahc = asyncHttpClient()) { final AtomicInteger headers = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(1); ahc.executeRequest(ahc.prepareGet(getTargetUrl()).build(), new AsyncHandler<Object>() { public void onThrowable(Throwable t) { fail("Got throwable.", t); assertTrue(latch.await(1, TimeUnit.SECONDS), "Latch failed."); } catch (InterruptedException e) { fail("Interrupted.", e); assertFalse(err.get()); assertEquals(queue.size(), 0); assertTrue(status.get());
@Test(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(); } }
@Test public void testNonProxyHostsRequestOverridesConfig() { ProxyServer configProxy = proxyServer("localhost", port1 - 1).build(); ProxyServer requestProxy = proxyServer("localhost", port1).setNonProxyHost("localhost").build(); try (AsyncHttpClient client = asyncHttpClient(config().setProxyServer(configProxy))) { String target = "http://localhost:1234/"; client.prepareGet(target).setProxyServer(requestProxy).execute().get(); assertFalse(true); } catch (Throwable e) { assertNotNull(e.getCause()); assertEquals(e.getCause().getClass(), ConnectException.class); } }
@Test public void testGlobalDefaultPerRequestInfiniteTimeout() throws IOException { try (AsyncHttpClient client = asyncHttpClient(config().setRequestTimeout(100))) { Future<Response> responseFuture = client.prepareGet(getTargetUrl()).setRequestTimeout(-1).execute(); Response response = responseFuture.get(); assertNotNull(response); } catch (InterruptedException e) { fail("Interrupted.", e); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof TimeoutException); checkTimeoutMessage(e.getCause().getMessage(), true); } }
@Test(enabled = false) public void relativeLocationUrl() throws Exception { isSet.getAndSet(false); try (AsyncHttpClient c = asyncHttpClient()) { Response response = c.preparePost(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", "/foo/test").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(response.getUri().toString(), getTargetUrl()); } }
@Test public void replayHeaderResponseFilterTest() throws Exception { final AtomicBoolean replay = new AtomicBoolean(true); ResponseFilter responseFilter = new ResponseFilter() { public <T> FilterContext<T> filter(FilterContext<T> ctx) { if (ctx.getResponseHeaders() != null && ctx.getResponseHeaders().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"); } }
@Test public void basic401Test() throws Exception { try (AsyncHttpClient client = asyncHttpClient()) { BoundRequestBuilder r = client.prepareGet(getTargetUrl()) .setHeader("X-401", "401") .setRealm(basicAuthRealm(USER, ADMIN).build()); Future<Integer> f = r.execute(new AsyncHandler<Integer>() { assertNotNull(statusCode); assertEquals(statusCode.intValue(), 401);
@Test(groups = "online", enabled = false) public void redirected302InvalidTest() throws Exception { isSet.getAndSet(false); Exception e = null; try (AsyncHttpClient c = asyncHttpClient()) { c.preparePost(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", String.format("http://localhost:%d/", port2)).execute().get(); } catch (ExecutionException ex) { e = ex; } assertNotNull(e); Throwable cause = e.getCause(); assertTrue(cause instanceof ConnectException); assertTrue(cause.getMessage().contains(":" + port2)); }
@Test public void testStreamingPutImage() throws Exception { try (AsyncHttpClient client = asyncHttpClient(config().setRequestTimeout(100 * 6000))) { Response response = client.preparePut(getTargetUrl()).setBody(createAsyncPublisher(LARGE_IMAGE_BYTES, 2342)) .execute().get(); assertEquals(response.getStatusCode(), 200); assertEquals(response.getResponseBodyAsBytes(), LARGE_IMAGE_BYTES); } }
@Test(enabled = false) public void redirected302InvalidTest() throws Exception { isSet.getAndSet(false); Exception e = null; try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) { c.prepareGet(getTargetUrl()).setHeader("X-redirect", String.format("http://localhost:%d/", port2)).execute().get(); } catch (ExecutionException ex) { e = ex; } assertNotNull(e); Throwable cause = e.getCause(); assertTrue(cause instanceof ConnectException); assertTrue(cause.getMessage().contains(":" + port2)); }
@Test public void urlWithColonTest() throws Exception { try (AsyncHttpClient c = asyncHttpClient()) { String query = "test:colon:"; Response response = c.prepareGet(String.format("http://localhost:%d/foo/test/colon?q=%s", port1, query)).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS); assertEquals(response.getHeader("q"), query); } }
@Test public void testClientStatusNoKeepalive() throws Throwable { try (final AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(false))) { final String url = getTargetUrl(); final ClientStats emptyStats = client.getClientStats(); assertEquals(emptyStats.toString(), "There are 0 total connections, 0 are active and 0 are idle."); assertEquals(emptyStats.getTotalActiveConnectionCount(), 0); assertEquals(emptyStats.getTotalIdleConnectionCount(), 0); assertEquals(emptyStats.getTotalConnectionCount(), 0); assertNull(emptyStats.getStatsPerHost().get(hostname)); Stream.generate(() -> client.prepareGet(url).setHeader("LockThread", "6").execute()) .limit(5) .collect(Collectors.toList()); final ClientStats activeStats = client.getClientStats(); assertEquals(activeStats.toString(), "There are 5 total connections, 5 are active and 0 are idle."); Stream.generate(() -> client.prepareGet(url).setHeader("LockThread", "6").execute()) .limit(3) .collect(Collectors.toList());
@Test public void maxConnectionsText() throws Exception { try (AsyncHttpClient c = asyncHttpClient(config().addRequestFilter(new ThrottleRequestFilter(0, 1000)))) { c.preparePost(getTargetUrl()).execute().get(); fail("Should have timed out"); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof FilterException); } }