Refine search
@Test(enabled = false) public void relativeLocationUrl() throws Exception { redirectDone.getAndSet(false); AsyncHttpClientConfig cg = config() .setMaxRedirects(5) .setFollowRedirect(true) .setUseInsecureTrustManager(true) .build(); try (AsyncHttpClient c = asyncHttpClient(cg)) { Response response = c.prepareGet(getTargetUrl()).setHeader("X-redirect", "/foo/test").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(response.getUri().toString(), getTargetUrl()); } }
@Test public void testHEAD302() throws IOException, InterruptedException, ExecutionException, TimeoutException { AsyncHttpClientConfig clientConfig = new DefaultAsyncHttpClientConfig.Builder().setFollowRedirect(true).build(); try (AsyncHttpClient client = asyncHttpClient(clientConfig)) { final CountDownLatch l = new CountDownLatch(1); Request request = head("http://localhost:" + port1 + "/Test").build(); Response response = client.executeRequest(request, new AsyncCompletionHandlerBase() { @Override public Response onCompleted(Response response) throws Exception { l.countDown(); return super.onCompleted(response); } }).get(3, TimeUnit.SECONDS); if (l.await(TIMEOUT, TimeUnit.SECONDS)) { assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); assertTrue(response.getUri().getPath().endsWith("_moved")); } else { fail("Timeout out"); } } }
@Test public void testMaxConnectionsWithinThreads() throws Exception { .setConnectTimeout(1000) .setRequestTimeout(5000) .setKeepAlive(true) .setMaxConnections(1) .setMaxConnectionsPerHost(1) .build(); assertEquals(failedCount.get(), 1, "Max Connections should have been reached when launching from concurrent threads"); client.prepareGet(url).execute(new AsyncCompletionHandlerBase() { @Override public Response onCompleted(Response response) throws Exception { assertEquals(failedCount.get(), 1, "Max Connections should have been reached when launching from main thread");
@Test 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); } } }
@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 regular302LosesBody() throws Exception { try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) { String body = "hello there"; String contentType = "text/plain; charset=UTF-8"; Response response = c.preparePost(getTargetUrl()).setHeader(CONTENT_TYPE, contentType).setBody(body).setHeader("X-REDIRECT", "302").execute().get(TIMEOUT, TimeUnit.SECONDS); assertEquals(response.getResponseBody(), ""); assertNull(receivedContentType); } }
@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 multipleMaxConnectionOpenTestWithQuery() throws Exception { try (AsyncHttpClient c = asyncHttpClient(config().setKeepAlive(true).setConnectTimeout(5000).setMaxConnections(1))) { String body = "hello there"; // once Response response = c.preparePost(getTargetUrl() + "?foo=bar").setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS); assertEquals(response.getResponseBody(), "foo_" + body); // twice Exception exception = null; try { response = c.preparePost(getTargetUrl()).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS); } catch (Exception ex) { ex.printStackTrace(); exception = ex; } assertNull(exception); assertNotNull(response); assertEquals(response.getStatusCode(), 200); } }
@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 public void testGlobalRequestTimeout() throws IOException { try (AsyncHttpClient client = asyncHttpClient(config().setRequestTimeout(100))) { Future<Response> responseFuture = client.prepareGet(getTargetUrl()).execute(); Response response = responseFuture.get(2000, TimeUnit.MILLISECONDS); assertNull(response); } catch (InterruptedException e) { fail("Interrupted.", e); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof TimeoutException); checkTimeoutMessage(e.getCause().getMessage(), true); } catch (TimeoutException e) { fail("Timeout.", e); } }
@Test public void basicAuthFileNoKeepAliveTest() throws Exception { try (AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(false))) { Future<Response> f = client.preparePost(getTargetUrl()) .setBody(SIMPLE_TEXT_FILE) .setRealm(basicAuthRealm(USER, ADMIN).build()) .execute(); Response resp = f.get(3, TimeUnit.SECONDS); assertNotNull(resp); assertNotNull(resp.getHeader("X-Auth")); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); assertEquals(resp.getResponseBody(), SIMPLE_TEXT_FILE_STRING); } }
@Test(enabled = false) public void httpToHttpsProperConfig() throws Exception { redirectDone.getAndSet(false); AsyncHttpClientConfig cg = config() .setMaxRedirects(5) .setFollowRedirect(true) .setUseInsecureTrustManager(true) .build(); try (AsyncHttpClient c = asyncHttpClient(cg)) { Response response = c.prepareGet(getTargetUrl()).setHeader("X-redirect", getTargetUrl2() + "/test2").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(response.getHeader("X-httpToHttps"), "PASS"); // Test if the internal channel is downgraded to clean http. response = c.prepareGet(getTargetUrl()).setHeader("X-redirect", getTargetUrl2() + "/foo2").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(response.getHeader("X-httpToHttps"), "PASS"); } }
@Test(groups = "online", enabled = false) public void notRedirected302Test() throws Exception { isSet.getAndSet(false); try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) { Response response = c.prepareGet(getTargetUrl()).setFollowRedirect(false).setHeader("X-redirect", "http://www.microsoft.com/").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 302); } }
@Test public void asyncStream302RedirectWithBody() throws Throwable { withClient(config().setFollowRedirect(true)).run(client -> withServer(server).run(server -> { String originalUrl = server.getHttpUrl() + "/original"; String redirectUrl = server.getHttpUrl() + "/redirect"; server.enqueueResponse(response -> { response.setStatus(302); response.setHeader(LOCATION.toString(), redirectUrl); response.getOutputStream().println("You are being asked to redirect to " + redirectUrl); }); server.enqueueOk(); Response response = client.prepareGet(originalUrl).execute().get(20, TimeUnit.SECONDS); assertEquals(response.getStatusCode(), 200); assertTrue(response.getResponseBody().isEmpty()); })); }
@Test public void redirectAndBasicAuthTest() throws Exception { try (AsyncHttpClient client = asyncHttpClient(config().setFollowRedirect(true).setMaxRedirects(10))) { Future<Response> f = client.prepareGet(getTargetUrl2()) .setRealm(basicAuthRealm(USER, ADMIN).build()) .execute(); Response resp = f.get(3, TimeUnit.SECONDS); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); assertNotNull(resp); assertNotNull(resp.getHeader("X-Auth")); } }
@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 basicPutFileTest() throws Exception { final AtomicReference<Throwable> throwable = new AtomicReference<>(); try (AsyncHttpClient client = asyncHttpClient(config().setConnectTimeout(timeout))) { TransferCompletionHandler tl = new TransferCompletionHandler(); tl.addTransferListener(new TransferListener() { Response response = client.preparePut(getTargetUrl()).setBody(file).execute(tl).get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertNotNull(hRead.get()); assertNotNull(hSent.get()); assertEquals(bbReceivedLenght.get(), file.length(), "Number of received bytes incorrect");
@Test(expectedExceptions = UnsupportedOperationException.class) public void deferredInputStreamTrickWithCloseConnectionAndRetry() throws Throwable { try (AsyncHttpClient client = asyncHttpClient(config().setMaxRequestRetry(1).setRequestTimeout(10000).build())) { BoundRequestBuilder r = client.prepareGet(getTargetUrl()).addHeader("X-CLOSE-CONNECTION", Boolean.TRUE.toString()); PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); BodyDeferringAsyncHandler bdah = new BodyDeferringAsyncHandler(pos); Future<Response> f = r.execute(bdah); BodyDeferringInputStream is = new BodyDeferringInputStream(f, bdah, pis); Response resp = is.getAsapResponse(); assertNotNull(resp); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); assertEquals(resp.getHeader(CONTENT_LENGTH), String.valueOf(CONTENT_LENGTH_VALUE)); // "consume" the body, but our code needs input stream CountingOutputStream cos = new CountingOutputStream(); try { try { copy(is, cos); } finally { is.close(); cos.close(); } } catch (IOException e) { throw e.getCause(); } } }
@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 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); } }