Example usage for org.apache.http.impl.client HttpClientBuilder setProxy

List of usage examples for org.apache.http.impl.client HttpClientBuilder setProxy

Introduction

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

Prototype

public final HttpClientBuilder setProxy(final HttpHost proxy) 

Source Link

Document

Assigns default proxy value.

Usage

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);// ww w.  j a v  a2  s .  c o m

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}

From source file:org.springframework.social.openidconnect.api.impl.GAECompatibleClientHttpRequestFactorySelector.java

public static ClientHttpRequestFactory getRequestFactory() {
    Properties properties = System.getProperties();
    String proxyHost = properties.getProperty("http.proxyHost");
    int proxyPort = properties.containsKey("http.proxyPort")
            ? Integer.valueOf(properties.getProperty("http.proxyPort"))
            : 80;//from  w ww .  j  ava 2  s .c om
    if (HTTP_COMPONENTS_AVAILABLE) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        if (proxyHost != null) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClientBuilder.setProxy(proxy);
        }
        return HttpComponentsClientRequestFactoryCreator.createRequestFactory(httpClientBuilder.build(),
                proxyHost, proxyPort);
    } else {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        if (proxyHost != null) {
            requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
        }
        return requestFactory;
    }
}

From source file:com.hp.autonomy.iod.client.RestAdapterFactory.java

public static RestAdapter getRestAdapter(final boolean withInterceptor, final Endpoint endpoint) {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    final String proxyHost = System.getProperty("hp.iod.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(System.getProperty("hp.iod.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }/*w w  w  .j  a  va 2 s. com*/

    final RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder().setEndpoint(endpoint.getUrl())
            .setClient(new ApacheClient(builder.build())).setConverter(new IodConverter())
            .setErrorHandler(new IodErrorHandler());

    if (withInterceptor) {
        restAdapterBuilder.setRequestInterceptor(new ApiKeyRequestInterceptor(endpoint.getApiKey()));
    }

    return restAdapterBuilder.build();
}

From source file:com.hp.autonomy.hod.client.HodServiceConfigFactory.java

public static HodServiceConfig<EntityType.Application, TokenType.Simple> getHodServiceConfig(
        final TokenProxyService<EntityType.Application, TokenType.Simple> tokenProxyService,
        final Endpoint endpoint) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableCookieManagement();/*from w ww.  j  a v  a2s.  c o  m*/
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60000).build());

    final String proxyHost = System.getProperty("hp.hod.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(System.getProperty("hp.hod.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }

    final HodServiceConfig.Builder<EntityType.Application, TokenType.Simple> configBuilder = new HodServiceConfig.Builder<EntityType.Application, TokenType.Simple>(
            endpoint.getUrl()).setHttpClient(builder.build());

    if (tokenProxyService != null) {
        configBuilder.setTokenProxyService(tokenProxyService);
    }

    return configBuilder.build();
}

From source file:groovesquid.Grooveshark.java

public static String sendRequest(String method, HashMap<String, Object> parameters) {
    if (tokenExpires <= new Date().getTime() && tokenExpires != 0 && !"initiateSession".equals(method)
            && !"getCommunicationToken".equals(method) && !"getCountry".equals(method)) {
        try {// ww  w. j  a  va  2  s  .  c  o m
            InitThread initThread = new InitThread();
            initThread.start();
            initThread.getLatch().await();
        } catch (InterruptedException ex) {
            log.log(Level.SEVERE, null, ex);
        }
    }
    String responseContent = null;
    HttpEntity httpEntity = null;
    try {
        Client client = clients.getHtmlshark();

        String protocol = "http://";

        if (method.equals("getCommunicationToken")) {
            protocol = "https://";
        }

        String url = protocol + "grooveshark.com/more.php?" + method;

        for (String jsqueueMethod : jsqueueMethods) {
            if (jsqueueMethod.equals(method)) {
                client = clients.getJsqueue();
                break;
            }
        }

        header.put("client", client.getName());
        header.put("clientRevision", client.getRevision());
        header.put("privacy", "0");
        header.put("uuid", uuid);
        header.put("country", country);
        if (!method.equals("initiateSession")) {
            header.put("session", session);
            header.put("token", generateToken(method, client.getSecret()));
        }

        Gson gson = new Gson();
        String jsonString = gson.toJson(new JsonRequest(header, parameters, method));
        log.info(">>> " + jsonString);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        httpPost.setHeader(HTTP.USER_AGENT,
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
        httpPost.setHeader("Referer", "http://grooveshark.com/JSQueue.swf?" + client.getRevision());
        httpPost.setHeader("Content-Language", "en-US");
        httpPost.setHeader("Cache-Control", "max-age=0");
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.3");
        httpPost.setHeader("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
        httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch");
        httpPost.setHeader("Origin", "http://grooveshark.com");
        if (!method.equals("initiateSession")) {
            httpPost.setHeader("Cookie", "PHPSESSID=" + session);
        }
        httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        if (Main.getConfig().getProxyHost() != null && Main.getConfig().getProxyPort() != null) {
            httpClientBuilder
                    .setProxy(new HttpHost(Main.getConfig().getProxyHost(), Main.getConfig().getProxyPort()));
        }
        HttpClient httpClient = httpClientBuilder.build();
        HttpResponse httpResponse = httpClient.execute(httpPost);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        httpEntity = httpResponse.getEntity();

        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity.writeTo(baos);
        } else {
            throw new RuntimeException("method " + method + ": " + statusLine);
        }

        responseContent = baos.toString("UTF-8");

    } catch (Exception ex) {
        Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            EntityUtils.consume(httpEntity);
        } catch (IOException ex) {
            Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    log.info("<<< " + responseContent);
    return responseContent;
}

From source file:eu.delving.sip.base.HttpClientFactory.java

private static void handleProxy(String serverUrl, HttpClientBuilder builder) {
    try {//from w ww.  j a  va  2s.c om
        List<Proxy> proxies = ProxySelector.getDefault().select(new URI(serverUrl));
        for (Proxy proxy : proxies) {
            if (proxy.type() != Proxy.Type.HTTP)
                continue;
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            builder.setProxy(new HttpHost(host, port));
        }
    } catch (URISyntaxException e) {
        throw new RuntimeException("Bad address: " + serverUrl, e);
    }
}

From source file:eu.esdihumboldt.util.http.client.ClientProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * //from   w  ww.  j  a  v  a 2s  .c  o m
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    ProxyUtil.init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    createCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:eu.esdihumboldt.util.http.ProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * /*  w  w  w  .ja  v  a  2 s  .  com*/
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    new UsernamePasswordCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:com.github.caldav4j.functional.support.CalDavFixture.java

private static HttpClient configureHttpClient(final CaldavCredential credential) {
    // HttpClient 4 requires a Cred providers, to be added during creation of client
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(credential.user, credential.password));

    // Default Host setting
    HttpRoutePlanner routePlanner = new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE) {

        @Override//from   w  w  w.  j a va  2s.co  m
        public HttpRoute determineRoute(final HttpHost target, final HttpRequest request,
                final HttpContext context) throws HttpException {
            return super.determineRoute(
                    target != null ? target
                            : new HttpHost(credential.host, credential.port, credential.protocol),
                    request, context);
        }

    };

    HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setRoutePlanner(routePlanner);

    if (credential.getProxyHost() != null) {
        builder.setProxy(new HttpHost(credential.getProxyHost(),
                (credential.getProxyPort() > 0) ? credential.getProxyPort() : 8080));
    }

    return builder.build();
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

    // Proxy/*from   w ww .j ava 2  s. c  o m*/
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }

    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }

    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(20);//max connection

    System.setProperty("jsse.enableSNIExtension", "false"); //""
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();

    client.setHttpclient(httpClient);
    return client;
}