Example usage for org.apache.http.client.config RequestConfig custom

List of usage examples for org.apache.http.client.config RequestConfig custom

Introduction

In this page you can find the example usage for org.apache.http.client.config RequestConfig custom.

Prototype

public static RequestConfig.Builder custom() 

Source Link

Usage

From source file:no.kantega.publishing.jobs.xmlimport.XMLImportJob.java

@PostConstruct
private void init() {
    int timeout = configuration.getInt("httpclient.connectiontimeout", 10000);
    String proxyHost = configuration.getString("httpclient.proxy.host");
    String proxyPort = configuration.getString("httpclient.proxy.port");

    String proxyUser = configuration.getString("httpclient.proxy.username");

    String proxyPassword = configuration.getString("httpclient.proxy.password");
    if (isNotBlank(proxyHost)) {
        HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));

        httpClientBuilder = HttpClients.custom()
                .setDefaultRequestConfig(
                        RequestConfig.custom().setRedirectsEnabled(true).setConnectTimeout(timeout)
                                .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build())
                .setProxy(proxy);//from w  w  w.  j a v  a2s  .  c om

        if (isNotBlank(proxyUser)) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    } else {
        httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(
                RequestConfig.custom().setRedirectsEnabled(true).setConnectTimeout(timeout)
                        .setSocketTimeout(timeout).setConnectionRequestTimeout(timeout).build());
    }
}

From source file:org.nuxeo.connect.downloads.LocalDownloadingPackage.java

@Override
public void run() {
    setPackageState(PackageState.REMOTE);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, sourceUrl);
    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        setPackageState(PackageState.DOWNLOADING);
        HttpGet method = new HttpGet(sourceUrl);
        if (!sourceUrl.contains(ConnectUrlConfig.CONNECT_TEST_MODE_BASEURL + "test")) { // for testing
            Map<String, String> headers = SecurityHeaderGenerator.getHeaders();
            for (String headerName : headers.keySet()) {
                method.addHeader(headerName, headers.get(headerName));
            }/*from  w w w.  java2  s . c  o  m*/
        }
        try (CloseableHttpResponse httpResponse = httpClient.execute(method)) {
            int rc = httpResponse.getStatusLine().getStatusCode();
            switch (rc) {
            case HttpStatus.SC_OK:
                if (sourceSize == 0) {
                    Header clheader = httpResponse.getFirstHeader("content-length");
                    if (clheader != null) {
                        sourceSize = Long.parseLong(clheader.getValue());
                    }
                }
                InputStream in = httpResponse.getEntity().getContent();
                saveStreamAsFile(in);
                registerDownloadedPackage();
                setPackageState(PackageState.DOWNLOADED);
                break;

            case HttpStatus.SC_NOT_FOUND:
                throw new ConnectServerError(String.format("Package not found (%s).", rc));
            case HttpStatus.SC_FORBIDDEN:
                throw new ConnectServerError(String.format("Access refused (%s).", rc));
            case HttpStatus.SC_UNAUTHORIZED:
                throw new ConnectServerError(String.format("Registration required (%s).", rc));
            default:
                serverError = true;
                throw new ConnectServerError(String.format("Connect server HTTP response code %s.", rc));
            }
        }
    } catch (IOException e) { // Expected SocketTimeoutException or ConnectTimeoutException
        serverError = true;
        setPackageState(PackageState.REMOTE);
        log.debug(e, e);
        errorMessage = e.getMessage();
    } catch (ConnectServerError e) {
        setPackageState(PackageState.REMOTE);
        log.debug(e, e);
        errorMessage = e.getMessage();
    } finally {
        ConnectDownloadManager cdm = NuxeoConnectClient.getDownloadManager();
        cdm.removeDownloadingPackage(getId());
        completed = true;
    }
}

From source file:org.brutusin.rpc.client.http.HttpEndpoint.java

public HttpEndpoint(URI endpoint, Config cfg, HttpClientContextFactory clientContextFactory) {
    if (endpoint == null) {
        throw new IllegalArgumentException("Endpoint is required");
    }//w  w  w  . j a v  a 2 s  .c o  m
    if (cfg == null) {
        cfg = new ConfigurationBuilder().build();
    }
    CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(cfg.getMaxCacheEntries())
            .setMaxObjectSize(cfg.getMaxCacheObjectSize()).build();
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1000 * cfg.getConnectTimeOutSeconds())
            .setSocketTimeout(1000 * cfg.getSocketTimeOutSeconds()).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(cfg.getMaxConections());

    this.endpoint = endpoint;
    this.httpClient = CachingHttpClients.custom().setCacheConfig(cacheConfig)
            .setDefaultRequestConfig(requestConfig).setRetryHandler(new StandardHttpRequestRetryHandler())
            .setConnectionManager(cm).build();
    this.clientContextFactory = clientContextFactory;
    initPingThread(cfg.getPingSeconds());
}

From source file:org.exoplatform.outlook.mail.MailAPI.java

/**
 * Instantiates a new mail API.//from w  w  w . j a v  a2 s.  c  o m
 *
 * @param httpClient the http client
 * @throws MailServerException the mail server exception
 */
MailAPI(CloseableHttpClient httpClient) throws MailServerException {

    if (httpClient == null) {
        // FYI it's possible make more advanced conn manager settings (host verification X509, conn config,
        // message parser etc.)
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        // 2 recommended by RFC 2616 sec 8.1.4, we make it bigger for quicker // upload
        connectionManager.setDefaultMaxPerRoute(10);
        connectionManager.setMaxTotal(100);

        // Create global request configuration
        RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true)
                .setStaleConnectionCheckEnabled(true).setAuthenticationEnabled(true)
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                // .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                // .setCookieSpec(CookieSpecs.BEST_MATCH)
                .build();

        // Create HTTP client
        this.httpClient = HttpClients.custom().setConnectionManager(connectionManager)
                // .setDefaultCredentialsProvider(credsProvider)
                .setDefaultRequestConfig(defaultRequestConfig).build();
    } else {
        // Use given HTTP client (for tests)
        this.httpClient = httpClient;
    }

    // Default header (Accept JSON), add to those requests where required
    this.acceptJsonHeader = new BasicHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());

    // Add AuthCache to the execution context
    this.httpContext = HttpClientContext.create();
}

From source file:com.helger.httpclient.HttpClientHelper.java

@Nonnull
public static HttpContext createHttpContext(@Nullable final HttpHost aProxy,
        @Nullable final Credentials aProxyCredentials) {
    final HttpClientContext ret = HttpClientContext.create();
    if (aProxy != null) {
        ret.setRequestConfig(RequestConfig.custom().setProxy(aProxy).build());
        if (aProxyCredentials != null) {
            final CredentialsProvider aCredentialsProvider = new BasicCredentialsProvider();
            aCredentialsProvider.setCredentials(new AuthScope(aProxy), aProxyCredentials);
            ret.setCredentialsProvider(aCredentialsProvider);
        }/*w w w.j a v  a 2  s.  c  o  m*/
    }
    return ret;
}

From source file:org.rapidoid.http.HttpClientUtil.java

private static RequestConfig reqConfig(HttpReq config) {
    return RequestConfig.custom().setSocketTimeout(config.socketTimeout())
            .setConnectTimeout(config.connectTimeout())
            .setConnectionRequestTimeout(config.connectionRequestTimeout()).build();
}

From source file:org.jboss.additional.testsuite.jdkall.present.jaxrs.client.ApacheHttpClient432TestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)/* www . j ava2s  .  c o m*/
public void apacheHttpClient4EngineServletTest(@ArquillianResource URL url) throws Exception {
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true)
            .setSoReuseAddress(true).build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

    connManager.setMaxTotal(100);

    connManager.setDefaultMaxPerRoute(100);

    connManager.setDefaultSocketConfig(socketConfig);

    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(100)
            .setConnectionRequestTimeout(3000).setStaleConnectionCheckEnabled(true).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .setConnectionManager(connManager).build();

    final ClientHttpEngine executor;

    executor = new ApacheHttpClient43Engine(httpClient);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(executor).build();

    final ApacheHttpClient43Resource proxy = client
            .target("http://127.0.0.1:8080/" + ApacheHttpClient432TestCase.class.getSimpleName())
            .proxy(ApacheHttpClient43Resource.class);

    WebTarget target = client
            .target("http://127.0.0.1:8080/" + ApacheHttpClient432TestCase.class.getSimpleName() + "/test2");

    Response response = target.request().get();
    Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());

    try {
        Response s = proxy.get();

        assertEquals(200, s.getStatus());
    } catch (ProcessingException e) {
        logger.warn("Exception occured." + e);

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

/**
 * @param uri the URI to open// ww w.  j  a  va  2 s. c o m
 */
@objid("bcf11edd-2a78-43ac-bf86-c0b0d059c536")
public ApacheUriConnection(URI uri) {
    this.uri = uri;
    this.configBuilder = RequestConfig.custom();
}

From source file:com.digitalpebble.storm.crawler.protocol.httpclient.HttpProtocol.java

@Override
public void configure(final Config conf) {
    this.maxContent = ConfUtils.getInt(conf, "http.content.limit", 64 * 1024);
    String userAgent = getAgentString(ConfUtils.getString(conf, "http.agent.name"),
            ConfUtils.getString(conf, "http.agent.version"),
            ConfUtils.getString(conf, "http.agent.description"), ConfUtils.getString(conf, "http.agent.url"),
            ConfUtils.getString(conf, "http.agent.email"));

    this.responseTime = ConfUtils.getBoolean(conf, "http.store.responsetime", true);

    this.skipRobots = ConfUtils.getBoolean(conf, "http.skip.robots", false);

    robots = new HttpRobotRulesParser(conf);

    builder = HttpClients.custom().setUserAgent(userAgent).setConnectionManager(CONNECTION_MANAGER)
            .setConnectionManagerShared(true).disableRedirectHandling();

    String proxyHost = ConfUtils.getString(conf, "http.proxy.host", null);
    int proxyPort = ConfUtils.getInt(conf, "http.proxy.port", 8080);

    boolean useProxy = (proxyHost != null && proxyHost.length() > 0);

    // use a proxy?
    if (useProxy) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }/*from  ww  w  . ja  v a2  s.  c om*/

    int timeout = ConfUtils.getInt(conf, "http.timeout", 10000);
    requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
}

From source file:edu.mit.scratch.ScratchUserManager.java

public ScratchUserManager update() throws ScratchUserException {
    try {//from ww w.j  a v  a2 s .  c om
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid",
                this.session.getSessionID());
        final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken());
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        sessid.setDomain(".scratch.mit.edu");
        sessid.setPath("/");
        token.setDomain(".scratch.mit.edu");
        token.setPath("/");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(sessid);
        cookieStore.addCookie(token);
        cookieStore.addCookie(debug);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/messages/ajax/get-message-count/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",
                        "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                                + this.session.getCSRFToken())
                .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);

        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = jsonOBJ.keys();

        while (keys.hasNext()) {
            final String key = "" + keys.next();
            final Object o = jsonOBJ.get(key);
            final String val = "" + o;

            switch (key) {
            case "msg_count":
                this.message_count = Integer.parseInt(val);
                break;
            default:
                System.out.println("Missing reference:" + key);
                break;
            }
        }
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }

    return this;
}