Example usage for org.apache.http.impl.client CloseableHttpClient execute

List of usage examples for org.apache.http.impl.client CloseableHttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient execute.

Prototype

public <T> T execute(final HttpHost target, final HttpRequest request,
        final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException 

Source Link

Document

Executes a request using the default context and processes the response using the given response handler.

Usage

From source file:interoperabilite.webservice.client.ClientExecuteSOCKS.java

public static void main(String[] args) throws Exception {
    Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new MyConnectionSocketFactory()).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    try {//from   ww w  . j  a v a  2 s.c  om
        InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
        HttpClientContext context = HttpClientContext.create();
        context.setAttribute("socks.address", socksaddr);

        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        HttpGet request = new HttpGet("/");

        System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
        CloseableHttpResponse response = httpclient.execute(target, request, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.lxf.spider.client.ClientPreemptiveBasicAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {// www.ja  va  2  s  .  c  om

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientPreemptiveBasicAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("httpbin.org", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*  w w  w.  j  a v  a2  s .c  om*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.lxf.spider.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*  w  w w  . j  ava  2s.com*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("httpbin.org", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//from w w  w  .  j a  v a 2s.co m

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];//  ww w.  ja v  a 2  s.  c o m
    String password = args[1];
    String repo = args[2];
    String project = args[3];
    String tagname = args[4];
    String name = args[5];
    String body = args[6];
    String draft = args[7];
    String prerelease = args[8];
    String filesString = args[9];
    String[] filenames = filesString.split(";");

    GitHubClient gitHubClient = new GitHubClient("api.github.com");
    gitHubClient.setCredentials(username, password);

    Map<String, String> map = new HashMap<String, String>();
    map.put("tag_name", tagname);
    // map.put("target_commitish", "test");
    map.put("name", name);
    map.put("body", body);
    //      map.put("draft", draft);
    //      map.put("prerelease", prerelease);
    try {
        String string = "/repos/" + repo + "/" + project + "/releases";
        System.out.println(string);
        JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class);
        System.out.println(gitHubResponse);
        String id = gitHubResponse.get("id").getAsString();

        HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https");

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(username, password));

        HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(basicCredentialsProvider)
                .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf)
                .build();

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(httpHost, basicAuth);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(basicCredentialsProvider);
        context.setAuthCache(authCache);

        for (String filename : filenames) {
            File file = new File(filename);
            String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id
                    + "/assets?name=" + file.getName();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept", "application/vnd.github.manifold-preview");
            post.setHeader("Content-Type", "application/zip");
            post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length()));
            HttpResponse execute = client.execute(httpHost, post, context);
            execute.getEntity().getContent().close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:nl.nn.adapterframework.http.BaseHttpSender.java

public S getSender() throws IOException {
    sender = createSender();//from   ww w.  jav  a 2 s. c om
    if (sender == null)
        fail("sender not initialized");

    CloseableHttpClient httpClient = mock(CloseableHttpClient.class);

    //Mock all requests
    when(httpClient.execute(any(HttpHost.class), any(HttpRequestBase.class), any(HttpContext.class)))
            .thenAnswer(new HttpResponseMock());

    when(sender.getHttpClient()).thenReturn(httpClient);

    //Some default settings, url will be mocked.
    sender.setUrl("http://127.0.0.1/");
    sender.setIgnoreRedirects(true);
    sender.setVerifyHostname(false);
    sender.setAllowSelfSignedCertificates(true);

    return sender;
}