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:com.hp.mqm.client.AbstractMqmRestClient.java

/**
 * Constructor for AbstractMqmRestClient.
 *
 * @param connectionConfig MQM connection configuration, Fields 'location', 'domain', 'project' and 'clientType' must not be null or empty.
 *//*from  w  ww.  j a v a  2  s. c  o m*/
protected AbstractMqmRestClient(MqmConnectionConfig connectionConfig) {
    checkNotEmpty("Parameter 'location' must not be null or empty.", connectionConfig.getLocation());
    checkNotEmpty("Parameter 'sharedSpace' must not be null or empty.", connectionConfig.getSharedSpace());
    checkNotEmpty("Parameter 'clientType' must not be null or empty.", connectionConfig.getClientType());
    clientType = connectionConfig.getClientType();
    location = connectionConfig.getLocation();
    sharedSpace = connectionConfig.getSharedSpace();
    username = connectionConfig.getUsername();
    password = connectionConfig.getPassword();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(20);
    cookieStore = new BasicCookieStore();

    if (connectionConfig.getProxyHost() != null && !connectionConfig.getProxyHost().isEmpty()) {
        HttpHost proxy = new HttpHost(connectionConfig.getProxyHost(), connectionConfig.getProxyPort());

        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy)
                .setConnectTimeout(connectionConfig.getDefaultConnectionTimeout() != null
                        ? connectionConfig.getDefaultConnectionTimeout()
                        : DEFAULT_CONNECTION_TIMEOUT)
                .setSocketTimeout(connectionConfig.getDefaultSocketTimeout() != null
                        ? connectionConfig.getDefaultSocketTimeout()
                        : DEFAULT_SO_TIMEOUT)
                .build();

        if (connectionConfig.getProxyCredentials() != null) {
            AuthScope proxyAuthScope = new AuthScope(connectionConfig.getProxyHost(),
                    connectionConfig.getProxyPort());
            Credentials credentials = proxyCredentialsToCredentials(connectionConfig.getProxyCredentials());

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(proxyAuthScope, credentials);

            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                    .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig)
                    .build();
        } else {
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                    .setDefaultRequestConfig(requestConfig).build();
        }
    } else {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectionConfig.getDefaultConnectionTimeout() != null
                        ? connectionConfig.getDefaultConnectionTimeout()
                        : DEFAULT_CONNECTION_TIMEOUT)
                .setSocketTimeout(connectionConfig.getDefaultSocketTimeout() != null
                        ? connectionConfig.getDefaultSocketTimeout()
                        : DEFAULT_SO_TIMEOUT)
                .build();
        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore)
                .setDefaultRequestConfig(requestConfig).build();
    }
}

From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(//from  w w w  .  j  av  a  2 s . c om
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Constructs a new BCE client using the specified client configuration options (ex: max retry attempts, proxy
 * settings, etc), and request metric collector.
 *
 * @param config Configuration options specifying how this client will communicate with BCE (ex: proxy settings,
 *               retry count, etc.)./*from   w  w  w  . j a  va  2  s.  c  o  m*/
 *
 * @throws java.lang.IllegalArgumentException If config or signer is null.
 */
public BceHttpClient(BceClientConfiguration config, Signer signer) {
    checkNotNull(config, "config should not be null.");
    checkNotNull(signer, "signer should not be null.");
    this.config = config;
    this.signer = signer;
    this.connectionManager = this.createHttpClientConnectionManager();
    this.httpClient = this.createHttpClient(this.connectionManager);
    IdleConnectionReaper.registerConnectionManager(this.connectionManager);

    this.requestConfigBuilder = RequestConfig.custom();
    this.requestConfigBuilder.setConnectTimeout(config.getConnectionTimeoutInMillis());
    this.requestConfigBuilder.setStaleConnectionCheckEnabled(true);
    if (config.getLocalAddress() != null) {
        this.requestConfigBuilder.setLocalAddress(config.getLocalAddress());
    }

    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        this.proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        this.requestConfigBuilder.setProxy(this.proxyHttpHost);

        this.credentialsProvider = new BasicCredentialsProvider();
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();
        if (proxyUsername != null && proxyPassword != null) {
            this.credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }
}

From source file:cn.org.once.cstack.utils.JSONClient.java

public DockerResponse sendPostToRegistryHost(URI uri, String body, String contentType)
        throws JSONClientException {

    if (logger.isDebugEnabled()) {
        logger.debug("Send a post request to : " + uri);
        logger.debug("Body content : " + body);
        logger.debug("Content type : " + contentType);
    }/*  w w w  .  ja  va 2s. co m*/

    RequestConfig config = RequestConfig.custom().setSocketTimeout(1000 * 60 * 50)
            .setConnectTimeout(1000 * 60 * 50).build();
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(config);
    httpPost.addHeader("content-type", contentType);
    httpPost.addHeader("X-Registry-Auth", "123");
    HttpResponse response = null;
    StringWriter writer = new StringWriter();
    try {
        CloseableHttpClient httpclient = buildSecureHttpClient();
        httpPost.setEntity(new StringEntity(body));
        response = httpclient.execute(httpPost);
        IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
    } catch (IOException e) {
        throw new JSONClientException("Error in sendPostToRegistryHost method due to : " + e.getMessage(), e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Status code : " + response.getStatusLine().getStatusCode());
        logger.debug("Server response : " + writer.toString());
    }

    return new DockerResponse(response.getStatusLine().getStatusCode(), writer.toString());
}

From source file:info.bonjean.beluga.connection.BelugaHTTPClient.java

public HttpResponse requestGetStream(HttpGet get) throws ClientProtocolException, IOException {
    // we keep track of the request, as the only way to interrupt it cleanly
    // is by using #abort()
    streamRequest = get;/*from   w ww. j  a  va 2s.c o  m*/

    // TODO: use a different client with BasicHttpClientConnectionManager
    // for the streaming connection

    // no socket timeout, this may improve pause support
    // TODO: check if it is working as expected (also depends of the server)
    RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).build();
    get.setConfig(config);
    HttpResponse httpResponse = httpClient.execute(get);
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
        throw new IOException("Server reply: " + httpResponse.getStatusLine().getReasonPhrase());
    return httpResponse;
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public String doGetWithResponseHandler(String url, String[] replaceParams, String[] params) {
    String result;/*from   w  w  w.j  a va2 s. c o m*/
    // CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {
        if (replaceParams.length > 0) {
            for (int i = 0; i < replaceParams.length; i++) {
                Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.FINE, replaceParams[i],
                        params[i]);
                url = url.replaceAll(replaceParams[i], params[i]);
            }
        }

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpGet getMethod = new HttpGet(url);

        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(hcp.getExceptionMessage() + status);
            }
        };

        result = client.execute(getMethod, responseHandler);
        client.close();

    } catch (SocketTimeoutException ex) {
        result = hcp.getTimeoutMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        result = hcp.getFailMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

From source file:jp.co.ctc_g.jse.core.rest.springmvc.client.ProxyClientHttpRequestFactory.java

/**
 * ???????HttpClient????????/*from  w  w  w .  j  a v a2  s  .  c o m*/
 * {@inheritDoc}
 */
@Override
public void afterPropertiesSet() throws Exception {

    Assert.notNull(proxyHost, "(proxyHost)???");
    Assert.notNull(proxyPort, "??(proxyPort)???");

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    HttpClientBuilder builder = HttpClients.custom();
    builder.setConnectionManager(connectionManager);
    if (authentication) {
        Assert.notNull(username,
                "??true???????(username)???");
        Assert.notNull(password,
                "??true?????(password)???");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(
                new HttpHost(proxyHost, Integer.parseInt(proxyPort)));
        builder.setRoutePlanner(routePlanner);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build());
    CloseableHttpClient client = builder.build();
    setHttpClient(client);
}

From source file:org.cerberus.service.rest.impl.RestService.java

@Override
public AnswerItem<AppService> callREST(String servicePath, String requestString, String method,
        List<AppServiceHeader> headerList, List<AppServiceContent> contentList, String token, int timeOutMs) {
    AnswerItem result = new AnswerItem();
    AppService serviceREST = factoryAppService.create("", AppService.TYPE_REST, method, "", "", "", "", "", "",
            "", "", null, "", null);
    MessageEvent message = null;// w  w  w  .  ja v  a2s.  c  om

    if (StringUtils.isNullOrEmpty(servicePath)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_SERVICEPATHMISSING);
        result.setResultMessage(message);
        return result;
    }
    if (StringUtils.isNullOrEmpty(method)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_METHODMISSING);
        result.setResultMessage(message);
        return result;
    }
    // If token is defined, we add 'cerberus-token' on the http header.
    if (token != null) {
        headerList.add(
                factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null));
    }
    CloseableHttpClient httpclient;
    httpclient = HttpClients.createDefault();
    try {

        // Timeout setup.
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeOutMs).build();

        AppService responseHttp = null;

        switch (method) {
        case AppService.METHOD_HTTPGET:

            LOG.info("Start preparing the REST Call (GET). " + servicePath + " - " + requestString);

            servicePath = StringUtil.addQueryString(servicePath, requestString);
            serviceREST.setServicePath(servicePath);
            HttpGet httpGet = new HttpGet(servicePath);

            // Timeout setup.
            httpGet.setConfig(requestConfig);

            // Header.
            for (AppServiceHeader contentHeader : headerList) {
                httpGet.addHeader(contentHeader.getKey(), contentHeader.getValue());
            }
            serviceREST.setHeaderList(headerList);
            // Saving the service before the call Just in case it goes wrong (ex : timeout).
            result.setItem(serviceREST);

            LOG.info("Executing request " + httpGet.getRequestLine());
            responseHttp = executeHTTPCall(httpclient, httpGet);

            if (responseHttp != null) {
                serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
            }

            break;
        case AppService.METHOD_HTTPPOST:

            LOG.info("Start preparing the REST Call (POST). " + servicePath);

            serviceREST.setServicePath(servicePath);
            HttpPost httpPost = new HttpPost(servicePath);

            // Timeout setup.
            httpPost.setConfig(requestConfig);

            // Content
            if (!(StringUtil.isNullOrEmpty(requestString))) {
                InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
                InputStreamEntity reqEntity = new InputStreamEntity(stream);
                reqEntity.setChunked(true);
                httpPost.setEntity(reqEntity);
                serviceREST.setServiceRequest(requestString);
            } else {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (AppServiceContent contentVal : contentList) {
                    nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps));
                serviceREST.setContentList(contentList);
            }

            // Header.
            for (AppServiceHeader contentHeader : headerList) {
                httpPost.addHeader(contentHeader.getKey(), contentHeader.getValue());
            }
            serviceREST.setHeaderList(headerList);
            // Saving the service before the call Just in case it goes wrong (ex : timeout).
            result.setItem(serviceREST);

            LOG.info("Executing request " + httpPost.getRequestLine());
            responseHttp = executeHTTPCall(httpclient, httpPost);

            if (responseHttp != null) {
                serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
            } else {
                message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
                message.setDescription(message.getDescription().replace("%DESCRIPTION%",
                        "Any issue was found when calling the service. Coud be a reached timeout during the call (."
                                + timeOutMs + ")"));
                result.setResultMessage(message);
                return result;

            }

            break;
        }

        // Get result Content Type.
        if (responseHttp != null) {
            serviceREST.setResponseHTTPBodyContentType(AppServiceService.guessContentType(serviceREST,
                    AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON));
        }

        result.setItem(serviceREST);
        message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", method));
        message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath));
        result.setResultMessage(message);

    } catch (SocketTimeoutException ex) {
        LOG.info("Exception when performing the REST Call. " + ex.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_TIMEOUT);
        message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath));
        message.setDescription(message.getDescription().replace("%TIMEOUT%", String.valueOf(timeOutMs)));
        result.setResultMessage(message);
        return result;
    } catch (Exception ex) {
        LOG.error("Exception when performing the REST Call. " + ex.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
        message.setDescription(
                message.getDescription().replace("%DESCRIPTION%", "Error on CallREST : " + ex.toString()));
        result.setResultMessage(message);
        return result;
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            LOG.error(ex.toString());
        }
    }

    return result;
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * ??/*ww  w . j a  v  a2 s.  c o m*/
 *
 * @param request
 *            requestnull{@link NullPointerException}
 * @return HttpResponse HTTP?
 * @throws IOException
 *             HTTP?
 * @throws ClientProtocolException
 *             ????
 */
public HttpResponse execute(Request request) throws ClientProtocolException, IOException {
    if (request == null) {
        return null;
    }
    RequestBuilder requestBuilder = request.getMethod().requestbuilder().setUri(request.getUrl().toString());
    requestBuilder
            .setConfig(RequestConfig.custom().setConnectTimeout(getTimeout(request.getTimeout())).build());
    requestBuilder.addHeader(SystemHeader.X_CA_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
    requestBuilder.addHeader(SystemHeader.X_CA_NONCE, UUID.randomUUID().toString());
    requestBuilder.addHeader(SystemHeader.X_CA_KEY, appKey);
    if (testEnv) {
        requestBuilder.addHeader(SystemHeader.X_CA_STAGE, "test");
    }
    requestBuilder.build().getAllHeaders();
    initialBasicHeader(requestBuilder, request.getHeaders(), request.getUrl(), request.getFormBody(),
            request.getSignHeaderPrefixes());
    HttpEntity entity = getEntity(request);
    if (entity != null) {
        requestBuilder.setEntity(entity);
    }
    return httpClient.execute(requestBuilder.build());
}