Search in sources :

Example 11 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project camel by apache.

the class CxfRsConsumerWithBeanTest method sendPutRequest.

private void sendPutRequest(String uri) throws Exception {
    HttpPut put = new HttpPut(uri);
    StringEntity entity = new StringEntity("string");
    entity.setContentType("text/plain");
    put.setEntity(entity);
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpResponse response = httpclient.execute(put);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("c20string", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.close();
    }
}
Also used : StringEntity(org.apache.http.entity.StringEntity) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpResponse(org.apache.http.HttpResponse) HttpPut(org.apache.http.client.methods.HttpPut)

Example 12 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project camel by apache.

the class HttpComponentVerifier method verifyHttpConnectivity.

private void verifyHttpConnectivity(ResultBuilder builder, Map<String, Object> parameters) throws Exception {
    Optional<String> uri = getOption(parameters, "httpUri", String.class);
    CloseableHttpClient httpclient = createHttpClient(parameters);
    HttpUriRequest request = new HttpGet(uri.get());
    try (CloseableHttpResponse response = httpclient.execute(request)) {
        int code = response.getStatusLine().getStatusCode();
        String okCodes = getOption(parameters, "okStatusCodeRange", String.class).orElse("200-299");
        if (!HttpHelper.isStatusCodeOk(code, okCodes)) {
            if (code == 401) {
                // Unauthorized, add authUsername and authPassword to the list
                // of parameters in error
                builder.error(ResultErrorBuilder.withHttpCode(code).description(response.getStatusLine().getReasonPhrase()).parameter("authUsername").parameter("authPassword").build());
            } else if (code >= 300 && code < 400) {
                // redirect
                builder.error(ResultErrorBuilder.withHttpCode(code).description(response.getStatusLine().getReasonPhrase()).parameter("httpUri").attribute(ComponentVerifier.HTTP_REDIRECT, true).attribute(ComponentVerifier.HTTP_REDIRECT_LOCATION, () -> HttpUtil.responseHeaderValue(response, "location")).build());
            } else if (code >= 400) {
                // generic http error
                builder.error(ResultErrorBuilder.withHttpCode(code).description(response.getStatusLine().getReasonPhrase()).build());
            }
        }
    } catch (UnknownHostException e) {
        builder.error(ResultErrorBuilder.withException(e).parameter("httpUri").build());
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) UnknownHostException(java.net.UnknownHostException) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 13 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project hive by apache.

the class TestHS2HttpServer method testConfStrippedFromWebUI.

@Test
public void testConfStrippedFromWebUI() throws Exception {
    String pwdValFound = null;
    String pwdKeyFound = null;
    CloseableHttpClient httpclient = null;
    try {
        httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://localhost:" + webUIPort + "/conf");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity1.getContent()));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(metastorePasswd)) {
                    pwdValFound = line;
                }
                if (line.contains(ConfVars.METASTOREPWD.varname)) {
                    pwdKeyFound = line;
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
    assertNotNull(pwdKeyFound);
    assertNull(pwdValFound);
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) Test(org.junit.Test)

Example 14 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project cryptomator by cryptomator.

the class WelcomeController method checkForUpdates.

private void checkForUpdates() {
    checkForUpdatesStatus.setText(localization.getString("welcome.checkForUpdates.label.currentlyChecking"));
    checkForUpdatesIndicator.setVisible(true);
    asyncTaskService.asyncTaskOf(() -> {
        RequestConfig requestConfig = //
        RequestConfig.custom().setConnectTimeout(//
        5000).setConnectionRequestTimeout(//
        5000).setSocketTimeout(//
        5000).build();
        HttpClientBuilder httpClientBuilder = //
        HttpClients.custom().disableCookieManagement().setDefaultRequestConfig(//
        requestConfig).setUserAgent("Cryptomator VersionChecker/" + ApplicationVersion.orElse("SNAPSHOT"));
        LOG.debug("Checking for updates...");
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            HttpGet request = new HttpGet("https://cryptomator.org/downloads/latestVersion.json");
            try (CloseableHttpResponse response = client.execute(request)) {
                if (response.getStatusLine().getStatusCode() == 200 && response.getEntity() != null) {
                    try (InputStream in = response.getEntity().getContent()) {
                        Gson gson = new GsonBuilder().setLenient().create();
                        Reader utf8Reader = new InputStreamReader(in, StandardCharsets.UTF_8);
                        Map<String, String> map = gson.fromJson(utf8Reader, new TypeToken<Map<String, String>>() {
                        }.getType());
                        if (map != null) {
                            this.compareVersions(map);
                        }
                    }
                }
            }
        }
    }).andFinally(() -> {
        checkForUpdatesStatus.setText("");
        checkForUpdatesIndicator.setVisible(false);
    }).run();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) Gson(com.google.gson.Gson) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) TypeToken(com.google.gson.reflect.TypeToken) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 15 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project webmagic by code4craft.

the class HttpClientDownloaderTest method testGetHtmlCharset.

@Test
public void testGetHtmlCharset() throws Exception {
    HttpServer server = httpserver(12306);
    server.get(by(uri("/header"))).response(header("Content-Type", "text/html; charset=gbk"));
    server.get(by(uri("/meta4"))).response(with(text("<html>\n" + "  <head>\n" + "    <meta charset='gbk'/>\n" + "  </head>\n" + "  <body></body>\n" + "</html>")), header("Content-Type", ""));
    server.get(by(uri("/meta5"))).response(with(text("<html>\n" + "  <head>\n" + "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\" />\n" + "  </head>\n" + "  <body></body>\n" + "</html>")), header("Content-Type", ""));
    Runner.running(server, new Runnable() {

        @Override
        public void run() {
            String charset = getCharsetByUrl("http://127.0.0.1:12306/header");
            assertEquals(charset, "gbk");
            charset = getCharsetByUrl("http://127.0.0.1:12306/meta4");
            assertEquals(charset, "gbk");
            charset = getCharsetByUrl("http://127.0.0.1:12306/meta5");
            assertEquals(charset, "gbk");
        }

        private String getCharsetByUrl(String url) {
            HttpClientDownloader downloader = new HttpClientDownloader();
            Site site = Site.me();
            CloseableHttpClient httpClient = new HttpClientGenerator().getClient(site, null);
            // encoding in http header Content-Type
            Request requestGBK = new Request(url);
            CloseableHttpResponse httpResponse = null;
            try {
                httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestGBK, site, null, null));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String charset = null;
            try {
                byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
                charset = downloader.getHtmlCharset(httpResponse, contentBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return charset;
        }
    });
}
Also used : Site(us.codecraft.webmagic.Site) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Runnable(com.github.dreamhead.moco.Runnable) HttpServer(com.github.dreamhead.moco.HttpServer) Request(us.codecraft.webmagic.Request) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)353 HttpGet (org.apache.http.client.methods.HttpGet)181 Test (org.junit.Test)178 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)172 HttpResponse (org.apache.http.HttpResponse)105 HttpEntity (org.apache.http.HttpEntity)82 IOException (java.io.IOException)75 HttpPost (org.apache.http.client.methods.HttpPost)62 StringEntity (org.apache.http.entity.StringEntity)59 InputStream (java.io.InputStream)40 StatusLine (org.apache.http.StatusLine)40 URI (java.net.URI)34 HttpHost (org.apache.http.HttpHost)29 RequestConfig (org.apache.http.client.config.RequestConfig)26 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)24 Header (org.apache.http.Header)20 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)19 AuthScope (org.apache.http.auth.AuthScope)18 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)18 CredentialsProvider (org.apache.http.client.CredentialsProvider)16