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 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); } }
@Test(expectedExceptions = IllegalArgumentException.class) public void nullSchemeThrowsNPE() throws Throwable { withClient().run(client -> client.prepareGet("gatling.io").execute()); }
@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(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)); }
private void expectSuccess(Function<BoundRequestBuilder, BoundRequestBuilder> f) throws Exception { File file = createTempFile(1024 * 1024); try (AsyncHttpClient client = asyncHttpClient()) { for (int i = 0; i < 20; i++) { Response response = f.apply(client.preparePut(getTargetUrl()) .addBodyPart(new FilePart("test", file, APPLICATION_OCTET_STREAM.toString(), UTF_8))) .execute().get(); assertEquals(response.getStatusCode(), 200); assertEquals(response.getResponseBodyAsBytes().length, Integer.valueOf(response.getHeader("X-" + CONTENT_LENGTH)).intValue()); } } }
protected void execute(String body) throws IOException, InterruptedException, ExecutionException { try (AsyncHttpClient client = asyncHttpClient()) { BoundRequestBuilder r = client.preparePost(getTargetUrl()).setBody(body).setCharset(UTF_8); Future<Response> f = r.execute(); Response resp = f.get(); assertEquals(resp.getStatusCode(), 200); assertEquals(body, resp.getResponseBody(UTF_8)); } } }
private WebSocket getWebSocket(final AsyncHttpClient c) throws Exception { return c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().build()).get(); }
@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 testParameters() throws IOException, ExecutionException, TimeoutException, InterruptedException { String value = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKQLMNOPQRSTUVWXYZ1234567809`~!@#$%^&*()_+-=,.<>/?;:'\"[]{}\\| "; try (AsyncHttpClient client = asyncHttpClient()) { Future<Response> f = client.preparePost("http://localhost:" + port1).addFormParam("test", value).execute(); Response resp = f.get(10, TimeUnit.SECONDS); assertNotNull(resp); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); assertEquals(resp.getHeader("X-Param"), value.trim()); } }
@Test public void testRequestTimeout() throws IOException { try (AsyncHttpClient client = asyncHttpClient()) { Future<Response> responseFuture = client.prepareGet(getTargetUrl()).setRequestTimeout(100).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(expectedExceptions = ConnectException.class) public void connectFailureThrowsConnectException() throws Throwable { withClient().run(client -> { int dummyPort = findFreePort(); try { client.preparePost(String.format("http://localhost:%d/", dummyPort)).execute(new AsyncCompletionHandlerAdapter() { @Override public void onThrowable(Throwable t) { } }).get(TIMEOUT, SECONDS); } catch (ExecutionException ex) { throw ex.getCause(); } }); }
private void put(int fileSize) throws Exception { File file = createTempFile(fileSize); try (AsyncHttpClient client = asyncHttpClient(config().setRequestTimeout(2000))) { Response response = client.preparePut(getTargetUrl()).setBody(file).execute().get(); assertEquals(response.getStatusCode(), 200); } }
private WebSocket getWebSocket(final AsyncHttpClient c, CountDownLatch closeLatch) throws Exception { return c.prepareGet(getTargetUrl()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketListener() { @Override public void onOpen(WebSocket websocket) { } @Override public void onError(Throwable t) { } @Override public void onClose(WebSocket websocket, int code, String reason) { closeLatch.countDown(); } }).build()).get(); } }
@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 zeroCopyPutTest() throws IOException, ExecutionException, InterruptedException { try (AsyncHttpClient client = asyncHttpClient()) { Future<Response> f = client.preparePut("http://localhost:" + port1 + "/").setBody(SIMPLE_TEXT_FILE).execute(); Response resp = f.get(); assertNotNull(resp); assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK); assertEquals(resp.getResponseBody(), SIMPLE_TEXT_FILE_STRING); } }
@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 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); } }
@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 loadThrottleTest() throws Exception { try (AsyncHttpClient c = asyncHttpClient(config().addRequestFilter(new ThrottleRequestFilter(10)))) { List<Future<Response>> futures = new ArrayList<>(); for (int i = 0; i < 200; i++) { futures.add(c.preparePost(getTargetUrl()).execute()); } for (Future<Response> f : futures) { Response r = f.get(); assertNotNull(f.get()); assertEquals(r.getStatusCode(), 200); } } }