Java Code Examples for org.apache.http.impl.client.HttpClients#createMinimal()

The following examples show how to use org.apache.http.impl.client.HttpClients#createMinimal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testGetWithoutPreCompression(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpGet request = new HttpGet(baseUri + "/compressed/foo_alone.txt");
        request.setHeader("Accept-Encoding", "gzip");
        try (CloseableHttpResponse res = hc.execute(request)) {
            assertThat(res.getFirstHeader("Content-Encoding")).isNull();
            assertThat(headerOrNull(res, "Content-Type")).isEqualTo(
                    "text/plain; charset=utf-8");
            final byte[] content = content(res);
            assertThat(new String(content, StandardCharsets.UTF_8)).isEqualTo("foo_alone");

            // Confirm path not cached when cache disabled.
            assertThat(PathAndQuery.cachedPaths())
                    .doesNotContain("/compressed/foo_alone.txt");
        }
    }
}
 
Example 2
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testOAuth2() throws Exception {
    final WebClient webClient = WebClient.builder(server.httpUri())
                                         .auth(OAuth2Token.of("dummy_oauth2_token"))
                                         .build();
    assertThat(webClient.get("/oauth2").aggregate().join().status()).isEqualTo(HttpStatus.OK);
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/oauth2-custom", OAuth2Token.of("dummy_oauth2_token"),
                                 CUSTOM_TOKEN_HEADER))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/oauth2", OAuth2Token.of("DUMMY_oauth2_token"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
    }
}
 
Example 3
Source File: ThriftSerializationFormatsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultSerializationFormat() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Send a TTEXT request with content type 'application/x-thrift' without 'protocol' parameter.
        final HttpPost req = new HttpPost(server.httpUri() + "/hellotextonly");
        req.setHeader("Content-type", "application/x-thrift");
        req.setEntity(new StringEntity(
                '{' +
                "  \"method\": \"hello\"," +
                "  \"type\":\"CALL\"," +
                "  \"args\": { \"name\": \"trustin\"}" +
                '}', StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
    }
}
 
Example 4
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testClassPathGetFromModule(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Read a class from a JDK module (java.base).
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(baseUri + "/classes/java/lang/Object.class"))) {
            assert200Ok(res, null, content -> assertThat(content).isNotEmpty());
        }
        // Read a class from a JDK module (java.base).
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(baseUri + "/by-entry/classes/java/lang/Object.class"))) {
            assert200Ok(res, null, content -> assertThat(content).isNotEmpty());
        }
    }
}
 
Example 5
Source File: WebAppContainerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
protected void testLarge(String path) throws IOException {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(new HttpGet(server().httpUri().resolve(path)))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
            assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue())
                    .startsWith("text/plain");

            final byte[] content = EntityUtils.toByteArray(res.getEntity());
            // Check if the content-length header matches.
            assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_LENGTH.toString()).getValue())
                    .isEqualTo(String.valueOf(content.length));

            // Check if the content contains what's expected.
            assertThat(Arrays.stream(CR_OR_LF.split(new String(content, StandardCharsets.UTF_8)))
                             .map(String::trim)
                             .filter(s -> !s.isEmpty())
                             .count()).isEqualTo(1024);
        }
    }
}
 
Example 6
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testFileSystemGet_newFile(String baseUri) throws Exception {
    final String barFileName = baseUri.substring(baseUri.lastIndexOf('/') + 1) + "_newFile.html";
    assertThat(barFileName).isIn("cached_newFile.html", "uncached_newFile.html");

    final Path barFile = tmpDir.resolve(barFileName);
    final String expectedContentA = "<html/>";

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpUriRequest req = new HttpGet(baseUri + "/fs/" + barFileName);
        try (CloseableHttpResponse res = hc.execute(req)) {
            assert404NotFound(res);
        }
        writeFile(barFile, expectedContentA);
        try (CloseableHttpResponse res = hc.execute(req)) {
            assert200Ok(res, "text/html", expectedContentA);
        }
    }
}
 
Example 7
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testReturnVoid() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        testStatusCode(hc, get("/1/void/204"), 204);
        testBodyAndContentType(hc, get("/1/void/200"), "200 OK", MediaType.PLAIN_TEXT_UTF_8.toString());
    }
}
 
Example 8
Source File: UnmanagedTomcatServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void unconfiguredWebApp() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(new HttpGet(server.httpUri() + "/no-webapp/"))) {
            // When no webapp is configured, Tomcat sends:
            // - 400 Bad Request response for 9.0.10+
            // - 404 Not Found for other versions
            final String statusLine = res.getStatusLine().toString();
            assertThat(statusLine).matches("^HTTP/1\\.1 (400 Bad Request|404 Not Found)$");
        }
    }
}
 
Example 9
Source File: ServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testDynamicRequestTimeoutInvocation() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpPost req = new HttpPost(server.httpUri() + "/timeout-not");
        req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(HttpStatusClass.valueOf(res.getStatusLine().getStatusCode()))
                    .isEqualTo(HttpStatusClass.SUCCESS);
        }
    }
}
 
Example 10
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testNonDefaultRoute() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Exact pattern
        testBody(hc, get("/6/exact"), "String[exact:/6/exact]");
        // Prefix pattern
        testBody(hc, get("/6/prefix/foo"), "String[prefix:/6/prefix/foo:/foo]");
        // Glob pattern
        testBody(hc, get("/6/glob1/bar"), "String[glob1:/6/glob1/bar]");
        testBody(hc, get("/6/baz/glob2"), "String[glob2:/6/baz/glob2:0]");
        // Regex pattern
        testBody(hc, get("/6/regex/foo/bar"), "String[regex:/6/regex/foo/bar:foo/bar]");
    }
}
 
Example 11
Source File: FileServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testIndexHtml(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(new HttpGet(baseUri + '/'))) {
            assert200Ok(res, "text/html", "<html><body></body></html>");
        }
    }
}
 
Example 12
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testOAuth1a() throws Exception {
    final OAuth1aToken passToken = OAuth1aToken.builder()
                                               .realm("dummy_realm")
                                               .consumerKey("dummy_consumer_key@#$!")
                                               .token("dummy_oauth1a_token")
                                               .signatureMethod("dummy")
                                               .signature("dummy_signature")
                                               .timestamp("0")
                                               .nonce("dummy_nonce")
                                               .version("1.0")
                                               .build();
    final WebClient webClient = WebClient.builder(server.httpUri())
                                         .auth(passToken)
                                         .build();
    assertThat(webClient.get("/oauth1a").aggregate().join().status()).isEqualTo(HttpStatus.OK);
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(
                oauth1aGetRequest("/oauth1a-custom", passToken, CUSTOM_TOKEN_HEADER))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        final OAuth1aToken failToken = OAuth1aToken.builder()
                                                   .realm("dummy_realm")
                                                   .consumerKey("dummy_consumer_key@#$!")
                                                   .token("dummy_oauth1a_token")
                                                   .signatureMethod("dummy")
                                                   .signature("DUMMY_signature") // This is different.
                                                   .timestamp("0")
                                                   .nonce("dummy_nonce")
                                                   .version("1.0")
                                                   .build();
        try (CloseableHttpResponse res = hc.execute(
                oauth1aGetRequest("/oauth1a", failToken, AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
    }
}
 
Example 13
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testServiceThrowHttpResponseException() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        testStatusCode(hc, get("/10/syncThrow401"), 401);
        testStatusCode(hc, get("/10/asyncThrow401"), 401);
        testStatusCode(hc, get("/10/asyncThrowWrapped401"), 401);
    }
}
 
Example 14
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthorizerException() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(server.httpUri() + "/authorizer_exception"))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
    }
}
 
Example 15
Source File: ServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testRequestTimeoutInvocation() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpPost req = new HttpPost(server.httpUri() + "/timeout");
        req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(HttpStatusClass.valueOf(res.getStatusLine().getStatusCode()))
                    .isNotEqualTo(HttpStatusClass.SUCCESS);
        }
    }
}
 
Example 16
Source File: MPCredentials.java    From dx-java with MIT License 5 votes vote down vote up
/**
 * Call the oauth api to get an access token
 *
 * @return                      a String with the access token
 * @throws MPException
 */
public static String getAccessToken() throws MPException {
    if (StringUtils.isEmpty(MercadoPago.SDK.getClientId()) ||
            StringUtils.isEmpty(MercadoPago.SDK.getClientSecret())) {
        throw new MPException("\"client_id\" and \"client_secret\" can not be \"null\" when getting the \"access_token\"");
    }

    JsonObject jsonPayload = new JsonObject();
    jsonPayload.addProperty("grant_type", "client_credentials");
    jsonPayload.addProperty("client_id", MercadoPago.SDK.getClientId());
    jsonPayload.addProperty("client_secret", MercadoPago.SDK.getClientSecret());

    String access_token = null;
    String baseUri = MercadoPago.SDK.getBaseUrl();

    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClients.createMinimal();

        MPApiResponse response = new MPRestClient(httpClient).executeRequest(
                HttpMethod.POST,
                baseUri + "/oauth/token",
                PayloadType.JSON,
                jsonPayload);

        if (response.getStatusCode() == 200) {
            JsonElement jsonElement = response.getJsonElementResponse();
            if (jsonElement.isJsonObject()) {
                access_token = ((JsonObject)jsonElement).get("access_token").getAsString();
            }
        } else {
            throw new MPException("Can not retrieve the \"access_token\"");
        }
    } finally {
        closeSilently(httpClient);
    }

    return access_token;
}
 
Example 17
Source File: ServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void testInvocation0(String path) throws IOException {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpPost req = new HttpPost(server.httpUri().resolve(path));
        req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
            assertThat(EntityUtils.toString(res.getEntity())).isEqualTo("Hello, world!");
        }
    }
}
 
Example 18
Source File: FileServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testClassPathOrElseGet(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal();
         CloseableHttpResponse res = hc.execute(new HttpGet(baseUri + "/bar.txt"))) {
        assert200Ok(res, "text/plain", "bar");
    }
}
 
Example 19
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testCompositeAuth() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(
                getRequest("/composite", "unit test"))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(
                basicGetRequest("/composite", BasicToken.of("brown", "cony"),
                                AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        final Map<String, String> passToken = ImmutableMap.<String, String>builder()
                .put("realm", "dummy_realm")
                .put("oauth_consumer_key", "dummy_consumer_key@#$!")
                .put("oauth_token", "dummy_oauth1a_token")
                .put("oauth_signature_method", "dummy")
                .put("oauth_signature", "dummy_signature")
                .put("oauth_timestamp", "0")
                .put("oauth_nonce", "dummy_nonce")
                .put("version", "1.0")
                .build();
        final OAuth1aToken oAuth1aToken = OAuth1aToken.builder().putAll(passToken).build();
        try (CloseableHttpResponse res = hc.execute(
                oauth1aGetRequest("/composite", oAuth1aToken, AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/composite", OAuth2Token.of("dummy_oauth2_token"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(new HttpGet(server.httpUri() + "/composite"))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
        try (CloseableHttpResponse res = hc.execute(
                basicGetRequest("/composite",
                                BasicToken.of("choco", "pangyo"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
    }
}
 
Example 20
Source File: CorsFilterLauncherTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected HttpClient client() {
    return HttpClients.createMinimal();
}