Example #1
1
  @Test(groups = "standalone", enabled = false)
  public void testProxyActivationProperty()
      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, "localhost");
    System.setProperty(
        AsyncHttpClientConfigDefaults.ASYNC_CLIENT_CONFIG_ROOT + "useProxyProperties", "true");
    AsyncHttpClientConfigHelper.reloadProperties();

    try (AsyncHttpClient client = asyncHttpClient()) {
      String proxifiedTarget = "http://127.0.0.1:1234/";
      Future<Response> f = client.prepareGet(proxifiedTarget).execute();
      Response resp = f.get(3, TimeUnit.SECONDS);
      assertNotNull(resp);
      assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
      assertEquals(resp.getHeader("target"), "/");

      String nonProxifiedTarget = "http://localhost:1234/";
      f = client.prepareGet(nonProxifiedTarget).execute();
      try {
        resp = f.get(3, TimeUnit.SECONDS);
        fail("should not be able to connect");
      } catch (ExecutionException e) {
        // ok, no proxy used
      }
    } finally {
      System.setProperties(originalProps);
    }
  }
  @Test(groups = "standalone")
  public void testObserveMultiple() {
    final TestSubscriber<Response> tester = new TestSubscriber<>();

    try (AsyncHttpClient client = asyncHttpClient()) {
      Observable<Response> o1 =
          AsyncHttpObservable.observe(() -> client.prepareGet("http://gatling.io"));
      Observable<Response> o2 =
          AsyncHttpObservable.observe(
              () -> client.prepareGet("http://www.wisc.edu").setFollowRedirect(true));
      Observable<Response> o3 =
          AsyncHttpObservable.observe(
              () -> client.prepareGet("http://www.umn.edu").setFollowRedirect(true));
      Observable<Response> all = Observable.merge(o1, o2, o3);
      all.subscribe(tester);
      tester.awaitTerminalEvent();
      tester.assertTerminalEvent();
      tester.assertCompleted();
      tester.assertNoErrors();
      List<Response> responses = tester.getOnNextEvents();
      assertNotNull(responses);
      assertEquals(responses.size(), 3);
      for (Response response : responses) {
        assertEquals(response.getStatusCode(), 200);
      }
    } catch (Exception e) {
      Thread.currentThread().interrupt();
    }
  }
  @Test(groups = {"standalone", "default_provider"})
  public void basicByteBufferTest() throws Exception {
    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      File largeFile = createTempFile(1024 * 100 * 10);
      final AtomicInteger byteReceived = new AtomicInteger();

      try {
        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());

      } catch (IOException ex) {
        fail("Should have timed out");
      }
    } finally {
      c.close();
    }
  }
Example #4
0
 @Test(groups = "standalone")
 public void testGlobalProxy()
     throws IOException, ExecutionException, TimeoutException, InterruptedException {
   try (AsyncHttpClient client =
       asyncHttpClient(config().setProxyServer(proxyServer("localhost", port1)))) {
     String target = "http://localhost:1234/";
     Future<Response> f = client.prepareGet(target).execute();
     Response resp = f.get(3, TimeUnit.SECONDS);
     assertNotNull(resp);
     assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
     assertEquals(resp.getHeader("target"), "/");
   }
 }
 @Test(groups = {"standalone", "default_provider"})
 public void Expect100Continue() throws Exception {
   try (AsyncHttpClient client = getAsyncHttpClient(null)) {
     Future<Response> f =
         client
             .preparePut("http://127.0.0.1:" + port1 + "/")
             .setHeader("Expect", "100-continue")
             .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(groups = { "standalone", "default_provider" })
  public void relativeLocationUrl() throws Exception {
    isSet.getAndSet(false);

    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      Response response =
          c.preparePost(getTargetUrl())
              .setFollowRedirect(true)
              .setHeader("X-redirect", "/foo/test")
              .execute()
              .get();
      assertNotNull(response);
      assertEquals(response.getStatusCode(), 302);
      assertEquals(response.getUri().toString(), getTargetUrl());
    } finally {
      c.close();
    }
  }
  // @Test(groups = { "online", "default_provider" })
  public void notRedirected302Test() throws Exception {
    isSet.getAndSet(false);
    AsyncHttpClientConfig cg = new AsyncHttpClientConfig.Builder().setFollowRedirect(true).build();
    AsyncHttpClient c = getAsyncHttpClient(cg);
    try {
      Response response =
          c.prepareGet(getTargetUrl())
              .setFollowRedirect(false)
              .setHeader("X-redirect", "http://www.microsoft.com/")
              .execute()
              .get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 302);
    } finally {
      c.close();
    }
  }
  @Test(groups = {"standalone", "default_provider"})
  public void testOmitErrorBody() throws Exception {
    SimpleAsyncHttpClient client =
        new SimpleAsyncHttpClient.Builder()
            .setProviderClass(getProviderClass())
            .setUrl(getTargetUrl() + "/nonexistent")
            .setErrorDocumentBehaviour(ErrorDocumentBehaviour.OMIT)
            .build();
    try {
      ByteArrayOutputStream o = new ByteArrayOutputStream(10);
      Future<Response> future = client.get(new OutputStreamBodyConsumer(o));

      System.out.println("waiting for response");
      Response response = future.get();
      assertEquals(response.getStatusCode(), 404);
      assertEquals(o.toString(), "");
      assertEquals(response.getResponseBody(), "");
    } finally {
      client.close();
    }
  }
  // @Test(groups = { "standalone", "default_provider" })
  public void redirected302InvalidTest() throws Exception {
    isSet.getAndSet(false);
    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      // If the test hit a proxy, no ConnectException will be thrown and instead of 404 will be
      // returned.
      Response response =
          c.preparePost(getTargetUrl())
              .setFollowRedirect(true)
              .setHeader("X-redirect", String.format("http://127.0.0.1:%d/", port2))
              .execute()
              .get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 404);
    } catch (ExecutionException ex) {
      assertEquals(ex.getCause().getClass(), ConnectException.class);
    } finally {
      c.close();
    }
  }
Example #10
0
  // @Test(groups = "standalone")
  public void testUseProxySelector()
      throws IOException, ExecutionException, TimeoutException, InterruptedException {
    ProxySelector originalProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(
        new ProxySelector() {
          public List<Proxy> select(URI uri) {
            if (uri.getHost().equals("127.0.0.1")) {
              return Arrays.asList(
                  new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port1)));
            } else {
              return Arrays.asList(Proxy.NO_PROXY);
            }
          }

          public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
        });

    try (AsyncHttpClient client = asyncHttpClient(config().setUseProxySelector(true))) {
      String proxifiedTarget = "http://127.0.0.1:1234/";
      Future<Response> f = client.prepareGet(proxifiedTarget).execute();
      Response resp = f.get(3, TimeUnit.SECONDS);
      assertNotNull(resp);
      assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
      assertEquals(resp.getHeader("target"), "/");

      String nonProxifiedTarget = "http://localhost:1234/";
      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 {
      // FIXME not threadsafe
      ProxySelector.setDefault(originalProxySelector);
    }
  }
  // @Test(groups = { "online", "default_provider" })
  public void redirected302Test() throws Exception {
    isSet.getAndSet(false);
    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      Response response =
          c.prepareGet(getTargetUrl())
              .setFollowRedirect(true)
              .setHeader("X-redirect", "http://www.microsoft.com/")
              .execute()
              .get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 200);

      String anyMicrosoftPage = "http://www.microsoft.com[^:]*:80";
      String baseUrl = getBaseUrl(response.getUri());

      assertTrue(
          baseUrl.matches(anyMicrosoftPage),
          "response does not show redirection to " + anyMicrosoftPage);
    } finally {
      c.close();
    }
  }