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

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

Introduction

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

Prototype

public void setProtocolVersion(final ProtocolVersion version) 

Source Link

Usage

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

public static HttpUriRequest getRequest(final HttpMethod method, final URI uri) {
    final HttpRequestBase request;
    switch (method) {
    case POST:/*from w  w  w  .  j  a  va  2 s . c  om*/
        request = new HttpPost(uri);// Request.Post(uri);
        break;
    case PUT:
        request = new HttpPut(uri);// Request.Put(uri);
        break;
    case DELETE:
        request = new HttpDelete(uri);// Request.Delete(uri);
        break;
    case GET:
        request = new HttpGet(uri);// Request.Get(uri);
        break;
    default:
        throw new IllegalStateException("UNSUPPORTED: " + method);
    }
    request.setProtocolVersion(HttpVersion.HTTP_1_1);
    final RequestConfig.Builder configBuilder = RequestConfig.custom();
    // TODO read (additional) HTTP client settings from external config
    configBuilder.setExpectContinueEnabled(true);
    request.setConfig(configBuilder.build());
    return request;
}

From source file:com.wudaosoft.net.httpclient.ParameterRequestBuilder.java

public static HttpUriRequest build(RequestBuilder builder) {

    final HttpRequestBase result;
    URI uriNotNull = builder.getUri() != null ? builder.getUri() : URI.create("/");
    Charset charset = builder.getCharset();
    charset = charset != null ? charset : HTTP.DEF_CONTENT_CHARSET;
    String method = builder.getMethod();
    List<NameValuePair> parameters = builder.getParameters();
    HttpEntity entityCopy = builder.getEntity();

    if (parameters != null && !parameters.isEmpty()) {
        if (entityCopy == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method)
                || HttpPut.METHOD_NAME.equalsIgnoreCase(method)
                || HttpPatch.METHOD_NAME.equalsIgnoreCase(method))) {
            entityCopy = new UrlEncodedFormEntity(parameters, charset);
        } else {//from w  ww  .java  2  s .c o m
            try {
                uriNotNull = new URIBuilder(uriNotNull).setCharset(charset).addParameters(parameters).build();
            } catch (final URISyntaxException ex) {
                // should never happen
            }
        }
    }

    if (entityCopy == null) {
        result = new InternalRequest(method);
    } else {
        final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method);
        request.setEntity(entityCopy);
        result = request;
    }
    result.setProtocolVersion(builder.getVersion());
    result.setURI(uriNotNull);
    // if (builder.headergroup != null) {
    // result.setHeaders(builder.headergroup.getAllHeaders());
    // }
    result.setConfig(builder.getConfig());
    return result;
}

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

/**
 * Creates a HttpRequest encoding a particular SOAP call.
 *
 * Called once per SOAP call./*from w  w  w.  j  a  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:com.okta.sdk.impl.http.httpclient.HttpClientRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request        The request to convert to an HttpClient method object.
 * @param previousEntity The optional, previous HTTP entity to reuse in the new request.
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 *//* w  w  w.j  a  v a  2 s.co  m*/
HttpRequestBase createHttpClientRequest(Request request, HttpEntity previousEntity) {

    HttpMethod method = request.getMethod();
    URI uri = getFullyQualifiedUri(request);
    InputStream body = request.getBody();
    long contentLength = request.getHeaders().getContentLength();

    HttpRequestBase base;

    switch (method) {
    case DELETE:
        base = new HttpDelete(uri);
        break;
    case GET:
        base = new HttpGet(uri);
        break;
    case HEAD:
        base = new HttpHead(uri);
        break;
    case POST:
        base = new HttpPost(uri);
        ((HttpEntityEnclosingRequestBase) base).setEntity(new RepeatableInputStreamEntity(request));
        break;
    case PUT:
        base = new HttpPut(uri);

        // Enable 100-continue support for PUT operations, since this is  where we're potentially uploading
        // large amounts of data and want to find out as early as possible if an operation will fail. We
        // don't want to do this for all operations since it will cause extra latency in the network
        // interaction.
        base.setConfig(RequestConfig.copy(defaultRequestConfig).setExpectContinueEnabled(true).build());

        if (previousEntity != null) {
            ((HttpEntityEnclosingRequestBase) base).setEntity(previousEntity);
        } else if (body != null) {
            HttpEntity entity = new RepeatableInputStreamEntity(request);
            if (contentLength < 0) {
                entity = newBufferedHttpEntity(entity);
            }
            ((HttpEntityEnclosingRequestBase) base).setEntity(entity);
        }
        break;
    default:
        throw new IllegalArgumentException("Unrecognized HttpMethod: " + method);
    }

    base.setProtocolVersion(HttpVersion.HTTP_1_1);

    applyHeaders(base, request);

    return base;
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

/**
 * Performs HTTP collection./*  ww w .  j av a 2s.  c o  m*/
 * 
 * Couple of notes to make the implementation of this client library
 * less obtuse:
 * 
 *   - HostConfiguration class is not created here because the library
 *     builds it when a URI is defined.
 *     
 * @param collectionSet
 * @throws HttpCollectorException
 */
private static void doCollection(final HttpCollectionSet collectionSet,
        final HttpCollectionResource collectionResource) throws HttpCollectorException {
    HttpRequestBase method = null;
    HttpClientWrapper clientWrapper = null;
    try {
        final HttpVersion httpVersion = computeVersion(collectionSet.getUriDef());

        clientWrapper = HttpClientWrapper.create()
                .setConnectionTimeout(ParameterMap.getKeyedInteger(collectionSet.getParameters(),
                        ParameterName.TIMEOUT.toString(), DEFAULT_SO_TIMEOUT))
                .setSocketTimeout(ParameterMap.getKeyedInteger(collectionSet.getParameters(),
                        ParameterName.TIMEOUT.toString(), DEFAULT_SO_TIMEOUT))
                .useBrowserCompatibleCookies();

        if ("https".equals(collectionSet.getUriDef().getUrl().getScheme())) {
            clientWrapper.useRelaxedSSL("https");
        }

        String key = ParameterName.RETRY.toString();
        if (collectionSet.getParameters().containsKey(ParameterName.RETRIES.toString())) {
            key = ParameterName.RETRIES.toString();
        }
        Integer retryCount = ParameterMap.getKeyedInteger(collectionSet.getParameters(), key,
                DEFAULT_RETRY_COUNT);
        clientWrapper.setRetries(retryCount);

        method = buildHttpMethod(collectionSet);
        method.setProtocolVersion(httpVersion);
        final String userAgent = determineUserAgent(collectionSet);
        if (userAgent != null && !userAgent.trim().isEmpty()) {
            clientWrapper.setUserAgent(userAgent);
        }
        final HttpClientWrapper wrapper = clientWrapper;

        if (collectionSet.getUriDef().getUrl().getUserInfo() != null) {
            final String userInfo = collectionSet.getUriDef().getUrl().getUserInfo();
            final String[] streetCred = userInfo.split(":", 2);
            if (streetCred.length == 2) {
                wrapper.addBasicCredentials(streetCred[0], streetCred[1]);
            } else {
                LOG.warn("Illegal value found for username/password HTTP credentials: {}", userInfo);
            }
        }

        LOG.info("doCollection: collecting using method: {}", method);
        final CloseableHttpResponse response = clientWrapper.execute(method);
        //Not really a persist as such; it just stores data in collectionSet for later retrieval
        persistResponse(collectionSet, collectionResource, response);
    } catch (URISyntaxException e) {
        throw new HttpCollectorException("Error building HttpClient URI", e);
    } catch (IOException e) {
        throw new HttpCollectorException("IO Error retrieving page", e);
    } catch (PatternSyntaxException e) {
        throw new HttpCollectorException("Invalid regex specified in HTTP collection configuration", e);
    } catch (Throwable e) {
        throw new HttpCollectorException("Unexpected exception caught during HTTP collection", e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}