Example usage for org.apache.http.client.protocol HttpClientContext REQUEST_CONFIG

List of usage examples for org.apache.http.client.protocol HttpClientContext REQUEST_CONFIG

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext REQUEST_CONFIG.

Prototype

String REQUEST_CONFIG

To view the source code for org.apache.http.client.protocol HttpClientContext REQUEST_CONFIG.

Click Source Link

Document

Attribute name of a org.apache.http.client.config.RequestConfig object that represents the actual request configuration.

Usage

From source file:com.github.ljtfreitas.restify.http.client.request.apache.httpclient.ApacheHttpClientRequestFactory.java

private HttpContext configure(HttpUriRequest httpRequest) {
    if (httpContext.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
        RequestConfig configuration = Optional.ofNullable(requestConfig)
                .orElseGet(() -> buildNewConfiguration());

        httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, configuration);
    }//from  w  w  w . jav a  2s  .  c  om

    return httpContext;
}

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

protected void initializeRequest(HttpRequestBase request, HttpClientContext context) {
    if (request.getFirstHeader("user-agent") == null) {
        request.setHeader("User-Agent", useragent);
    }//w w  w  .  java2s  .c  om

    for (Header requestHeader : requestHeaders) {
        request.setHeader(requestHeader);
    }

    RequestConfig.Builder configBuilder = RequestConfig
            .copy(request.getConfig() == null ? RequestConfig.DEFAULT : request.getConfig());

    if (timeoutMS != null) {
        configBuilder.setConnectTimeout(timeoutMS);
        configBuilder.setConnectionRequestTimeout(timeoutMS);
        configBuilder.setSocketTimeout(timeoutMS);
    }

    if (maxRedirect == 0) {
        configBuilder.setRedirectsEnabled(false);
    } else {
        configBuilder.setMaxRedirects(maxRedirect);
    }

    RequestConfig config = configBuilder.build();

    context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
    request.setConfig(config);
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

private void configureTimeout(final HttpClientBuilder builder, final int timeout) {
    final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(timeout);
    builder.setDefaultRequestConfig(requestBuilder.build());

    builder.setDefaultSocketConfig(createSocketConfigBuilder(timeout).build());

    httpContext_.removeAttribute(HttpClientContext.REQUEST_CONFIG);
    usedOptions_.setTimeout(timeout);/*from  w w  w. j  a v a  2 s.  c  o  m*/
}

From source file:org.apache.http.impl.client.InternalHttpClient.java

private void setupContext(final HttpClientContext context) {
    if (context.getAttribute(HttpClientContext.TARGET_AUTH_STATE) == null) {
        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, new AuthState());
    }/*  w ww  .  jav a  2  s  . co m*/
    if (context.getAttribute(HttpClientContext.PROXY_AUTH_STATE) == null) {
        context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, new AuthState());
    }
    if (context.getAttribute(HttpClientContext.AUTHSCHEME_REGISTRY) == null) {
        context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry);
    }
    if (context.getAttribute(HttpClientContext.COOKIESPEC_REGISTRY) == null) {
        context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);
    }
    if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) {
        context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
    }
    if (context.getAttribute(HttpClientContext.CREDS_PROVIDER) == null) {
        context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider);
    }
    if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
        context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.defaultConfig);
    }
}

From source file:org.restcomm.connect.http.client.Downloader.java

public HttpResponseDescriptor fetch(final HttpRequestDescriptor descriptor)
        throws IllegalArgumentException, IOException, URISyntaxException, XMLStreamException {
    int code = -1;
    HttpRequest request = null;//w w  w  .  ja  v  a  2  s.co  m
    CloseableHttpResponse response = null;
    HttpRequestDescriptor temp = descriptor;
    HttpResponseDescriptor responseDescriptor = null;
    HttpResponseDescriptor rawResponseDescriptor = null;
    try {
        do {
            request = request(temp);
            //FIXME:should we externalize RVD encoding default?
            request.setHeader("http.protocol.content-charset", "UTF-8");
            if (descriptor.getTimeout() > 0) {
                HttpContext httpContext = new BasicHttpContext();
                httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG,
                        RequestConfig.custom().setConnectTimeout(descriptor.getTimeout())
                                .setSocketTimeout(descriptor.getTimeout())
                                .setConnectionRequestTimeout(descriptor.getTimeout()).build());
                response = client.execute((HttpUriRequest) request, httpContext);
            } else {
                response = client.execute((HttpUriRequest) request);
            }
            code = response.getStatusLine().getStatusCode();
            if (isRedirect(code)) {
                final Header header = response.getFirstHeader(HttpHeaders.LOCATION);
                if (header != null) {
                    final String location = header.getValue();
                    final URI uri = URI.create(location);
                    temp = new HttpRequestDescriptor(uri, temp.getMethod(), temp.getParameters());
                    continue;
                } else {
                    break;
                }
            }
            //                HttpResponseDescriptor httpResponseDescriptor = response(request, response);
            rawResponseDescriptor = response(request, response);
            responseDescriptor = validateXML(rawResponseDescriptor);
        } while (isRedirect(code));
        if (isHttpError(code)) {
            // TODO - usually this part of code is not reached. Error codes are part of error responses that do not pass validateXML above and an exception is thrown. We need to re-thing this
            String requestUrl = request.getRequestLine().getUri();
            String errorReason = response.getStatusLine().getReasonPhrase();
            String httpErrorMessage = String.format(
                    "Problem while fetching http resource: %s \n Http status code: %d \n Http status message: %s",
                    requestUrl, code, errorReason);
            logger.warning(httpErrorMessage);
        }
    } catch (Exception e) {
        logger.warning("Problem while trying to download RCML from {}, exception: {}", request.getRequestLine(),
                e);
        String statusInfo = "n/a";
        String responseInfo = "n/a";
        if (response != null) {
            // Build additional information to log. Include http status, url and a small fragment of the response.
            statusInfo = response.getStatusLine().toString();
            if (rawResponseDescriptor != null) {
                int truncatedSize = (int) Math.min(rawResponseDescriptor.getContentLength(),
                        LOGGED_RESPONSE_MAX_SIZE);
                if (rawResponseDescriptor.getContentAsString() != null) {
                    responseInfo = String.format("%s %s",
                            rawResponseDescriptor.getContentAsString().substring(0, truncatedSize),
                            (rawResponseDescriptor.getContentLength() < LOGGED_RESPONSE_MAX_SIZE ? "" : "..."));
                }
            }
        }
        logger.warning(
                String.format("Problem while trying to download RCML. URL: %s, Status: %s, Response: %s ",
                        request.getRequestLine(), statusInfo, responseInfo));
        throw e; // re-throw
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return responseDescriptor;
}

From source file:org.restcomm.connect.http.client.rcmlserver.RcmlserverApi.java

public void transmitNotifications(List<JsonObject> notifications, String notifierUsername,
        String notifierPassword) {
    String notificationUrl = apiUrl + "/notifications";
    HttpPost request = new HttpPost(notificationUrl);
    String authHeader;//w  w  w .ja va  2s . c  o  m
    authHeader = SecurityUtils.buildBasicAuthHeader(notifierUsername, notifierPassword);
    request.setHeader("Authorization", authHeader);
    Gson gson = new Gson();
    String json = gson.toJson(notifications);
    request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    Integer totalTimeout = rcmlserverConfig.getTimeout()
            + notifications.size() * rcmlserverConfig.getTimeoutPerNotification();
    CloseableHttpAsyncClient httpClient = CustomHttpClientBuilder.buildCloseableHttpAsyncClient(mainConfig);
    if (logger.isDebugEnabled()) {
        logger.debug("Will transmit a set of " + notifications.size() + " "
                + "notifications and wait at most for " + totalTimeout);
    }
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG,
            RequestConfig.custom().setConnectTimeout(totalTimeout).setSocketTimeout(totalTimeout)
                    .setConnectionRequestTimeout(totalTimeout).build());
    httpClient.execute(request, httpContext, new RCMLCallback());
}