@Test public void testUrlRequestParametersEncoding() throws IOException, ExecutionException, InterruptedException { String URL = getTargetUrl() + "?q="; String REQUEST_PARAM = "github github \ngithub"; try (AsyncHttpClient client = asyncHttpClient()) { String requestUrl2 = URL + URLEncoder.encode(REQUEST_PARAM, UTF_8.name()); logger.info("Executing request [{}] ...", requestUrl2); Response response = client.prepareGet(requestUrl2).execute().get(); String s = URLDecoder.decode(response.getHeader("q"), UTF_8.name()); assertEquals(s, REQUEST_PARAM); } }
public static void main(String[] args) throws IOException { try (AsyncHttpClient asyncHttpClient = asyncHttpClient()) { asyncHttpClient .prepareGet("http://www.example.com/") .execute() .toCompletableFuture() .thenApply(Response::getResponseBody) .thenAccept(System.out::println) .join(); } } }
@Test public void testListenableFutureBeforeAndAfterCompletion() throws Exception { final CountDownLatch latch = new CountDownLatch(2); try (AsyncHttpClient ahc = asyncHttpClient()) { final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute(); future.addListener(latch::countDown, Runnable::run); future.get(); future.addListener(latch::countDown, Runnable::run); } latch.await(10, TimeUnit.SECONDS); } }
@Test public void streamedResponseSmallFileTest() throws Throwable { try (AsyncHttpClient c = asyncHttpClient()) { String smallFileName = "http://localhost:" + serverPort + "/" + smallFile.getName(); ListenableFuture<SimpleStreamedAsyncHandler> future = c.prepareGet(smallFileName).execute(new SimpleStreamedAsyncHandler()); byte[] result = future.get().getBytes(); LOGGER.debug("Result file size: " + result.length); assertEquals(result.length, smallFile.length()); } }
@Test public void testListenableFutureAfterCompletion() throws Exception { final CountDownLatch latch = new CountDownLatch(1); try (AsyncHttpClient ahc = asyncHttpClient()) { final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute(); future.get(); future.addListener(latch::countDown, Runnable::run); } latch.await(10, TimeUnit.SECONDS); }
@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 testListenableFuture() throws Exception { final AtomicInteger statusCode = new AtomicInteger(500); try (AsyncHttpClient ahc = asyncHttpClient()) { final CountDownLatch latch = new CountDownLatch(1); final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute(); future.addListener(() -> { try { statusCode.set(future.get().getStatusCode()); latch.countDown(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }, Executors.newFixedThreadPool(1)); latch.await(10, TimeUnit.SECONDS); assertEquals(statusCode.get(), 200); } }
@Test public void streamedResponseLargeFileTest() throws Throwable { try (AsyncHttpClient c = asyncHttpClient()) { String largeFileName = "http://localhost:" + serverPort + "/" + largeFile.getName(); ListenableFuture<SimpleStreamedAsyncHandler> future = c.prepareGet(largeFileName).execute(new SimpleStreamedAsyncHandler()); byte[] result = future.get().getBytes(); assertEquals(result.length, largeFile.length()); } }
@Test public void nonPoolableConnectionReleaseSemaphoresTest() throws Throwable { RequestBuilder request = get(getTargetUrl()).setHeader("Connection", "close"); try (AsyncHttpClient client = asyncHttpClient(config().setMaxConnections(6).setMaxConnectionsPerHost(3))) { client.executeRequest(request).get(); Thread.sleep(1000); client.executeRequest(request).get(); Thread.sleep(1000); client.executeRequest(request).get(); Thread.sleep(1000); client.executeRequest(request).get(); } }
@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(timeOut = 60000) public void onCloseWithCode() throws Exception { try (AsyncHttpClient c = asyncHttpClient()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> text = new AtomicReference<>(""); WebSocket websocket = c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new Listener(latch, text)).build()).get(); websocket.sendCloseFrame(); latch.await(); assertTrue(text.get().startsWith("1000"), "Expected a 1000 code but got " + text.get()); } }
@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 requestingPlainHttpEndpointOverHttpsThrowsSslException() throws Throwable { withClient().run(client -> withServer(server).run(server -> { server.enqueueEcho(); try { client.prepareGet(getTargetUrl().replace("http", "https")).execute().get(); fail("Request shouldn't succeed"); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof ConnectException, "Cause should be a ConnectException"); assertTrue(e.getCause().getCause() instanceof SSLException, "Root cause should be a SslException"); } })); }
@Test(timeOut = 60000) public void onCloseWithCodeServerClose() throws Exception { try (AsyncHttpClient c = asyncHttpClient()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> text = new AtomicReference<>(""); c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new Listener(latch, text)).build()).get(); latch.await(); assertEquals(text.get(), "1001-Idle Timeout"); } }
@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 testPutEmptyBody() throws Exception { try (AsyncHttpClient ahc = asyncHttpClient()) { Response response = ahc.preparePut(getTargetUrl()).setBody("String").execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 204); assertEquals(response.getResponseBody(), ""); assertNotNull(response.getResponseBodyAsStream()); assertEquals(response.getResponseBodyAsStream().read(), -1); } }
@Test public void basicByteBufferTest() throws Exception { try (AsyncHttpClient c = asyncHttpClient()) { File largeFile = createTempFile(1024 * 100 * 10); final AtomicInteger byteReceived = new AtomicInteger(); Response response = c.preparePut(getTargetUrl()).setBody(largeFile).execute(new AsyncCompletionHandlerAdapter() { @Override public State onBodyPartReceived(final HttpResponseBodyPart content) throws Exception { byteReceived.addAndGet(content.getBodyByteBuffer().capacity()); return super.onBodyPartReceived(content); } }).get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(byteReceived.get(), largeFile.length()); assertEquals(response.getResponseBody().length(), largeFile.length()); } }
@Test(enabled = false) public void absolutePathRedirectTest() throws Exception { isSet.getAndSet(false); try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) { String redirectTarget = "/bar/test"; String destinationUrl = new URI(getTargetUrl()).resolve(redirectTarget).toString(); Response response = c.prepareGet(getTargetUrl()).setHeader("X-redirect", redirectTarget).execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(response.getUri().toString(), destinationUrl); logger.debug("{} was redirected to {}", redirectTarget, destinationUrl); } }
@Test(enabled = false) public void relativePathRedirectTest() throws Exception { isSet.getAndSet(false); try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) { String redirectTarget = "bar/test1"; String destinationUrl = new URI(getTargetUrl()).resolve(redirectTarget).toString(); Response response = c.prepareGet(getTargetUrl()).setHeader("X-redirect", redirectTarget).execute().get(); assertNotNull(response); assertEquals(response.getStatusCode(), 200); assertEquals(response.getUri().toString(), destinationUrl); logger.debug("{} was redirected to {}", redirectTarget, destinationUrl); } }
@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); } }