Example usage for org.apache.http.client.methods HttpRequestBase setConfig

List of usage examples for org.apache.http.client.methods HttpRequestBase setConfig

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase setConfig.

Prototype

public void setConfig(final RequestConfig config) 

Source Link

Usage

From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java

protected void execute(HttpRequestBase httpBaseRequest, CredentialItem credentialItem, List<CookieItem> cookies)
        throws ClientProtocolException, IOException, URISyntaxException {

    if (!CollectionUtils.isEmpty(cookies)) {
        List<Cookie> cookieList = cookieStore.getCookies();
        for (CookieItem cookie : cookies) {
            Cookie newCookie = cookie.getCookie();
            if (!cookieList.contains(newCookie))
                cookieStore.addCookie(newCookie);
        }/*from   w  w w .j  av  a  2  s.  c  o  m*/
    }

    this.httpBaseRequest = httpBaseRequest;

    // No more than one 1 minute to establish the connection
    // No more than 10 minutes to establish the socket
    // Enable stales connection checking
    // Cookies uses browser compatibility
    RequestConfig.Builder configBuilber = RequestConfig.custom().setSocketTimeout(1000 * 60 * 10)
            .setConnectTimeout(1000 * 60).setStaleConnectionCheckEnabled(true)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);

    if (credentialItem == null)
        credentialsProvider.clear();
    else
        credentialItem.setUpCredentials(credentialsProvider);

    URI uri = httpBaseRequest.getURI();
    if (proxyHandler != null)
        proxyHandler.check(configBuilber, uri, credentialsProvider);

    httpBaseRequest.setConfig(configBuilber.build());

    httpClientContext = new HttpClientContext();

    httpResponse = httpClient.execute(httpBaseRequest, httpClientContext);
    if (httpResponse == null)
        return;
    statusLine = httpResponse.getStatusLine();
    httpEntity = httpResponse.getEntity();
}

From source file:org.fao.geonet.api.mapservers.GeoServerRest.java

/**
 * @param method      e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams   REST API parameter
 * @param postData    XML data/* ww w . j av a2 s  .c  o m*/
 * @param file        File to upload
 * @param contentType type of content in case of post data or file updload.
 */
public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file,
        String contentType, Boolean saveResponse) throws IOException {

    response = "";
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        if (postData != null)
            Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpRequestBase m;
    if (method.equals(METHOD_PUT)) {
        m = new HttpPut(url);
        if (file != null) {
            ((HttpPut) m)
                    .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING)));
        }

        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPut) m).setEntity(entity);
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new HttpDelete(url);
    } else if (method.equals(METHOD_POST)) {
        m = new HttpPost(url);
        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPost) m).setEntity(entity);
        }
    } else {
        m = new HttpGet(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setHeader("Content-type", contentType);
    }

    m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build());

    // apparently this is needed to preemptively send the auth, for servers that dont require it but
    // dont send the same data if you're authenticated or not.
    try {
        m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m));
    } catch (AuthenticationException a) {
        Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage());
    }
    ;

    final ClientHttpResponse httpResponse = factory.execute(m,
            new UsernamePasswordCredentials(username, password), AuthScope.ANY);

    try {
        status = httpResponse.getRawStatusCode();
        if (Log.isDebugEnabled(LOGGER_NAME)) {
            Log.debug(LOGGER_NAME, "status:" + status);
        }
        if (saveResponse) {
            this.response = IOUtils.toString(httpResponse.getBody());
        }
    } finally {
        httpResponse.close();
    }

    return status;
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String query(String dms_endpoint, String body, String method) throws SocketTimeoutException,
        ConnectException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    Cookie ck;//from  w w w.  j  a  v a  2  s  . com
    //String internalToken;
    CloseableHttpClient httpclient;
    HttpRequestBase httpaction;
    //boolean wasEmpty;
    //int code;
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    URI uri = null;
    try {
        // Prepare to forward the request to the proxy
        uri = new URI(dms_URL + "/" + dms_endpoint);
    } catch (URISyntaxException e1) {
        java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
    }

    if (method.equals("GET")) {
        httpaction = new HttpGet(uri);
    } else {
        httpaction = new HttpPost(uri);
    }

    // Get token or authenticate if null or invalid
    //internalToken = client.getToken();
    ck = new Cookie("vitalAccessToken", cookie.substring(17));

    httpaction.setHeader("Cookie", ck.toString());
    httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
            .setSocketTimeout(5000).build());
    httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON);
    StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8);
    if (method.equals("POST")) {
        ((HttpPost) httpaction).setEntity(strEntity);
    }

    // Execute and get the response.
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpaction);
    } catch (ClientProtocolException e) {
        java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e);
    } catch (IOException e) {
        try {
            // Try again with a higher timeout
            try {
                Thread.sleep(1000); // do not retry immediately
            } catch (InterruptedException e1) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
                return "";
            }
            httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000)
                    .setConnectTimeout(7000).setSocketTimeout(7000).build());
            response = httpclient.execute(httpaction);
        } catch (ClientProtocolException ea) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea);
            return "";
        } catch (IOException ea) {
            try {
                // Try again with a higher timeout
                try {
                    Thread.sleep(1000); // do not retry immediately
                } catch (InterruptedException e1) {
                    java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
                    return "";
                }
                httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000)
                        .setConnectTimeout(12000).setSocketTimeout(12000).build());
                response = httpclient.execute(httpaction);
            } catch (ClientProtocolException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                return "";
            } catch (SocketTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                return "";
            } catch (ConnectException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                return "";
            } catch (ConnectTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                return "";
            }
        }
    }

    int statusCode = response.getStatusLine().getStatusCode();
    String respString = "";

    HttpEntity entity = null;

    if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {

        entity = response.getEntity();

    } else {
        if (statusCode == 503) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 503");
            return "";
        } else if (statusCode == 502) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 502");
            return "";
        } else if (statusCode == 401) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 401");
            return "";
        } else {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "PPI 500");
            return "";
            //throw new ServiceUnavailableException();
        }

    }

    if (entity != null) {
        try {
            respString = EntityUtils.toString(entity);
            response.close();
        } catch (ParseException | IOException e) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, "PPI 401");
            return "";
        }
    }
    return respString;

}

From source file:org.fao.geonet.utils.AbstractHttpRequest.java

protected HttpRequestBase setupHttpMethod() throws IOException {
    String queryString = query;//from  w  w  w  . j  ava  2  s .  com

    if (query == null || query.trim().isEmpty()) {
        StringBuilder b = new StringBuilder();

        for (NameValuePair alSimpleParam : alSimpleParams) {
            if (b.length() > 0) {
                b.append("&");
            }
            b.append(alSimpleParam.getName()).append('=').append(alSimpleParam.getValue());
        }
        if (b.length() > 0) {
            queryString = b.toString();
        }
    }

    if (host == null || protocol == null) {
        throw new IllegalStateException(
                String.format(getClass().getSimpleName() + " is not ready to be executed: \n\tprotocol: '%s' "
                        + "\n\tuserinfo: '%s'\n\thost: '%s' \n\tport: '%s' \n\taddress: '%s'\n\tquery '%s'"
                        + "\n\tfragment: '%s'", protocol, userInfo, host, port, address, query, fragment));
    }

    HttpRequestBase httpMethod;

    if (method == Method.GET) {
        HttpGet get = new HttpGet();

        get.addHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
        httpMethod = get;
    } else {
        HttpPost post = new HttpPost();

        if (!useSOAP) {
            postData = (postParams == null) ? "" : Xml.getString(new Document(postParams));
            HttpEntity entity = new StringEntity(postData, ContentType.create("application/xml", "UTF-8"));
            post.setEntity(entity);
        } else {
            postData = Xml.getString(new Document(soapEmbed(postParams)));
            HttpEntity entity = new StringEntity(postData, ContentType.create("application/xml", "UTF-8"));
            post.setEntity(entity);
        }

        httpMethod = post;
    }

    try {
        URI uri = new URI(protocol, userInfo, host, port, address, queryString, fragment);
        httpMethod.setURI(uri);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    final RequestConfig.Builder builder = RequestConfig.custom();
    builder.setAuthenticationEnabled((credentials != null) || (proxyCredentials != null));
    builder.setRedirectsEnabled(true);
    builder.setRelativeRedirectsAllowed(true);
    builder.setCircularRedirectsAllowed(true);
    builder.setMaxRedirects(3);
    builder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);

    httpMethod.setConfig(builder.build());
    return httpMethod;
}

From source file:com.algolia.search.saas.APIClient.java

private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json,
        HashMap<String, String> errors) throws AlgoliaException {
    req.reset();/*w  w w. j  a  va  2 s  .  com*/

    // set URL
    try {
        req.setURI(new URI("https://" + host + url));
    } catch (URISyntaxException e) {
        // never reached
        throw new IllegalStateException(e);
    }

    // set auth headers
    req.setHeader("X-Algolia-Application-Id", this.applicationID);
    if (forwardAdminAPIKey == null) {
        req.setHeader("X-Algolia-API-Key", this.apiKey);
    } else {
        req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
        req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
        req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
    }
    for (Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
    }

    // set user agent
    req.setHeader("User-Agent", "Algolia for Java " + version);

    // set JSON entity
    if (json != null) {
        if (!(req instanceof HttpEntityEnclosingRequestBase)) {
            throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
        }
        req.setHeader("Content-type", "application/json");
        try {
            StringEntity se = new StringEntity(json, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            ((HttpEntityEnclosingRequestBase) req).setEntity(se);
        } catch (UnsupportedEncodingException e) {
            throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
        }
    }

    RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS)
            .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build();
    req.setConfig(config);

    HttpResponse response;
    try {
        response = httpClient.execute(req);
    } catch (IOException e) {
        // on error continue on the next host
        errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage()));
        return null;
    }
    try {
        int code = response.getStatusLine().getStatusCode();
        if (code / 100 == 4) {
            String message = "";
            try {
                message = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (code == 400) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
            } else if (code == 403) {
                throw new AlgoliaException(code,
                        message.length() > 0 ? message : "Invalid Application-ID or API-Key");
            } else if (code == 404) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
            } else {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
            }
        }
        if (code / 100 != 2) {
            try {
                errors.put(host, EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                errors.put(host, String.valueOf(code));
            }
            // KO, continue
            return null;
        }
        try {
            InputStream istream = response.getEntity().getContent();
            InputStreamReader is = new InputStreamReader(istream, "UTF-8");
            JSONTokener tokener = new JSONTokener(is);
            JSONObject res = new JSONObject(tokener);
            is.close();
            return res;
        } catch (IOException e) {
            return null;
        } catch (JSONException e) {
            throw new AlgoliaException("JSON decode error:" + e.getMessage());
        }
    } finally {
        req.releaseConnection();
    }
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java

public HttpResponse execute(HttpRequest request) throws IOException {
    URI uri = createURI(request);

    HttpRequestBase internalRequest;
    if (request.method == HttpMethod.HEAD) {
        internalRequest = new HttpHead(uri);
    } else {/*from  w  ww  .j  a  v a  2s .  c  om*/
        HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name());
        if (request.hasBody()) {
            ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8));
            String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE);
            if (Strings.hasLength(contentType)) {
                entity.setContentType(contentType);
            } else {
                entity.setContentType(ContentType.TEXT_PLAIN.toString());
            }
            methodWithEntity.setEntity(entity);
        }
        internalRequest = methodWithEntity;
    }
    internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());

    // headers
    if (request.headers().isEmpty() == false) {
        for (Map.Entry<String, String> entry : request.headers.entrySet()) {
            internalRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header!
    if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) {
        XContentType xContentType = XContentFactory.xContentType(request.body());
        if (xContentType != null) {
            internalRequest.setHeader("Content-Type", xContentType.mediaType());
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    setProxy(config, request, settingsProxy);
    HttpClientContext localContext = HttpClientContext.create();
    // auth
    if (request.auth() != null) {
        ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port));
        localContext.setCredentialsProvider(credentialsProvider);

        // preemptive auth, no need to wait for a 401 first
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth);
        localContext.setAuthCache(authCache);
    }

    // timeouts
    if (request.connectionTimeout() != null) {
        config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis()));
    } else {
        config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis()));
    }

    if (request.readTimeout() != null) {
        config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis()));
    } else {
        config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis()));
    }

    internalRequest.setConfig(config.build());

    try (CloseableHttpResponse response = SocketAccess
            .doPrivileged(() -> client.execute(internalRequest, localContext))) {
        // headers
        Header[] headers = response.getAllHeaders();
        Map<String, String[]> responseHeaders = new HashMap<>(headers.length);
        for (Header header : headers) {
            if (responseHeaders.containsKey(header.getName())) {
                String[] old = responseHeaders.get(header.getName());
                String[] values = new String[old.length + 1];

                System.arraycopy(old, 0, values, 0, old.length);
                values[values.length - 1] = header.getValue();

                responseHeaders.put(header.getName(), values);
            } else {
                responseHeaders.put(header.getName(), new String[] { header.getValue() });
            }
        }

        final byte[] body;
        // not every response has a content, i.e. 204
        if (response.getEntity() == null) {
            body = new byte[0];
        } else {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                try (InputStream is = new SizeLimitInputStream(maxResponseSize,
                        response.getEntity().getContent())) {
                    Streams.copy(is, outputStream);
                }
                body = outputStream.toByteArray();
            }
        }
        return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders);
    }
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates a HttpRequest encoding a particular SOAP call.
 *
 * Called once per SOAP call./*w w w  . ja v  a  2 s  .  c  o  m*/
 */
protected HttpUriRequest createHttpRequest(MessageContext msgContext, URI url) throws AxisFault {
    boolean posting = true;
    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
        if (webMethod != null) {
            posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
    }

    HttpRequestBase request = posting ? new HttpPost(url) : new HttpGet(url);

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";
    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    request.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    request.addHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");

    String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
        request.setProtocolVersion(HttpVersion.HTTP_1_0);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        Iterator i = mimeHeaders.getAllHeaders();
        while (i.hasNext()) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String name = mimeHeader.getName();
            if (!name.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    && !name.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                request.addHeader(name, mimeHeader.getValue());
            }
        }
    }

    boolean isChunked = false;
    boolean isExpectContinueEnabled = false;
    Map<?, ?> userHeaderTable = (Map) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
    if (userHeaderTable != null) {
        for (Map.Entry<?, ?> me : userHeaderTable.entrySet()) {
            Object keyObj = me.getKey();
            if (keyObj != null) {
                String key = keyObj.toString().trim();
                String value = me.getValue().toString().trim();
                if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    isExpectContinueEnabled = value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue);
                } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                    isChunked = JavaUtils.isTrue(value);
                } else {
                    request.addHeader(key, value);
                }
            }
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one definition of timeout */
        config.setSocketTimeout(msgContext.getTimeout()).setConnectTimeout(msgContext.getTimeout());
    } else if (clientProperties.getConnectionPoolTimeout() != 0) {
        config.setConnectTimeout(clientProperties.getConnectionPoolTimeout());
    }
    config.setContentCompressionEnabled(msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP));
    config.setExpectContinueEnabled(isExpectContinueEnabled);
    request.setConfig(config.build());

    if (request instanceof HttpPost) {
        HttpEntity requestEntity = new MessageEntity(request, msgContext.getRequestMessage(), isChunked);
        if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
            requestEntity = new GzipCompressingEntity(requestEntity);
        }
        ((HttpPost) request).setEntity(requestEntity);
    }

    return request;
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the {@link HttpUriRequest} implementation appropriate to
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxy} the specified
 * <code>pageRequest</code> to the <code>proxiedFileURL</code>.
 * /*w ww.j a  v a 2 s.  c  om*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param proxiedFileURL The {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}.
 * @return The created {@link HttpUriRequest}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient)
 * @see #PROXY_REQUEST_OBJ_HOOK
 */
protected HttpRequestBase createProxyRequestObject(final Page.Request pageRequest, final Mode mode,
        final URL proxiedFileURL) throws WWWEEEPortal.Exception, WebApplicationException {
    final RequestConfig requestConfig = createProxyClientRequestConfig(pageRequest, mode);

    final Object[] context = new Object[] { mode, proxiedFileURL, requestConfig };
    HttpRequestBase proxyRequest = PROXY_REQUEST_OBJ_HOOK.value(plugins, context, pageRequest);
    if (proxyRequest == null) {

        final URI proxiedFileURI;
        try {
            proxiedFileURI = proxiedFileURL.toURI();
        } catch (URISyntaxException urise) {
            throw new WWWEEEPortal.SoftwareException(urise);
        }

        final String method = pageRequest.getRSRequest().getMethod();
        if ((!pageRequest.isMaximized(this)) || (method.equalsIgnoreCase("GET"))) {
            proxyRequest = new HttpGet(proxiedFileURI);
        } else if (method.equalsIgnoreCase("HEAD")) {
            proxyRequest = new HttpHead(proxiedFileURI);
        } else if (method.equalsIgnoreCase("POST")) {
            proxyRequest = new HttpPost(proxiedFileURI);
        } else if (method.equalsIgnoreCase("PUT")) {
            proxyRequest = new HttpPut(proxiedFileURI);
        } else if (method.equalsIgnoreCase("DELETE")) {
            proxyRequest = new HttpDelete(proxiedFileURI);
        } else {
            throw new WebApplicationException(
                    Response.status(RESTUtil.Response.Status.METHOD_NOT_ALLOWED).build());
        }

        proxyRequest.setConfig(requestConfig);

    }
    proxyRequest = PROXY_REQUEST_OBJ_HOOK
            .requireFilteredResult(PROXY_REQUEST_OBJ_HOOK.filter(plugins, context, pageRequest, proxyRequest));
    return proxyRequest;
}