Example usage for org.apache.http.client.methods HttpHead HttpHead

List of usage examples for org.apache.http.client.methods HttpHead HttpHead

Introduction

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

Prototype

public HttpHead(final String uri) 

Source Link

Usage

From source file:com.norconex.collector.http.fetch.impl.GenericMetadataFetcher.java

@Override
public Properties fetchHTTPHeaders(HttpClient httpClient, String url) {
    Properties metadata = new Properties();
    HttpHead method = null;/* www.j a  v  a 2s .c o  m*/
    try {
        method = new HttpHead(url);
        // Execute the method.
        HttpResponse response = httpClient.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        if (!ArrayUtils.contains(validStatusCodes, statusCode)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Invalid HTTP status code (" + response.getStatusLine() + ") for URL: " + url);
            }
            return null;
        }
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];
            String name = header.getName();
            if (StringUtils.isNotBlank(headersPrefix)) {
                name = headersPrefix + name;
            }

            metadata.addString(name, header.getValue());
        }
        return metadata;
    } catch (Exception e) {
        LOG.error("Cannot fetch document: " + url + " (" + e.getMessage() + ")", e);
        throw new CollectorException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.dthume.spring.http.client.httpcomponents.HttpComponentsClientHttpRequest.java

private HttpUriRequest createRequest() {
    final URI requestUri = getURI();
    final HttpMethod requestMethod = getMethod();

    switch (requestMethod) {
    case DELETE:/*from   w ww  .  j  a  v a  2s  . c o  m*/
        return new HttpDelete(requestUri);
    case GET:
        return new HttpGet(requestUri);
    case HEAD:
        return new HttpHead(requestUri);
    case PUT:
        return new HttpPut(requestUri);
    case POST:
        return new HttpPost(requestUri);
    case OPTIONS:
        return new HttpOptions(requestUri);
    default:
        final String msg = "Unknown Http Method: " + requestMethod;
        throw new IllegalArgumentException(msg);
    }
}

From source file:org.hawk.http.HTTPManager.java

@Override
public String getCurrentRevision() throws Exception {
    try (final CloseableHttpClient cl = createClient()) {
        /*//from w ww.  j  av a 2  s.  com
         * Since HTTP servers can be quite varied, we try several methods in
         * sequence:
         *
         * - ETag headers are preferred, since these explicitly check for
         * changes. - Otherwise, Last-Modified dates are used. - Otherwise,
         * Content-Length is used.
         *
         * We try first a HEAD request, and if that doesn't work a GET
         * request.
         */

        final HttpHead headRequest = new HttpHead(repositoryURL);
        decorateCurrentRevisionRequest(headRequest);
        try (CloseableHttpResponse response = cl.execute(headRequest)) {
            String headRevision = getRevision(response);
            if (headRevision != null) {
                return headRevision;
            }
        }

        final HttpGet getRequest = new HttpGet(repositoryURL);
        decorateCurrentRevisionRequest(getRequest);
        try (CloseableHttpResponse response = cl.execute(getRequest)) {
            String getRev = getRevision(response);
            if (getRev != null) {
                return getRev;
            }
        }
    }

    // No way to detect changes - just fetch the file once
    return "1";
}

From source file:net.joala.expression.library.net.UriStatusCodeExpression.java

@Override
@Nonnull// w  ww . j ava 2 s .com
public Integer get() {
    final String host = uri.getHost();
    checkState(knownHost().matches(host), "Host %s from URI %s is unknown.", host, uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        final HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, (int) timeout.in(TimeUnit.MILLISECONDS));
        HttpConnectionParams.setSoTimeout(httpParams, (int) timeout.in(TimeUnit.MILLISECONDS));
        final HttpUriRequest httpHead = new HttpHead(uri);
        try {
            final HttpResponse response = httpClient.execute(httpHead);
            final HttpEntity httpEntity = response.getEntity();
            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();
            if (httpEntity != null) {
                EntityUtils.consume(httpEntity);
            }
            return statusCode;
        } catch (IOException e) {
            throw new ExpressionEvaluationException(format("Failure reading from URI %s.", uri), e);
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.qwazr.cluster.manager.ClusterNode.java

void startCheck(CloseableHttpAsyncClient httpclient) {
    checkToken = UUID.randomUUID().toString();
    HttpHead httpHead = new HttpHead(checkURI);
    httpHead.setHeader(ClusterServiceInterface.HEADER_CHECK_NAME, checkToken);
    httpHead.setHeader(ClusterServiceInterface.HEADER_CHECK_ADDR, ClusterManager.INSTANCE.myAddress);
    httpHead.setHeader("Connection", "close");
    latencyStart = System.currentTimeMillis();
    httpclient.execute(httpHead, this);
}

From source file:ai.eve.volley.stack.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from   w  ww  . j av  a  2 s . c  om
private static HttpUriRequest createHttpRequest(Request<?> request) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HTTP.CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HTTP.CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HTTP.CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.fcrepo.camel.FedoraClient.java

/**
 * Make a HEAD response/*from  w w  w  .j a  va  2 s .co  m*/
 */
public FedoraResponse head(final URI url)
        throws ClientProtocolException, IOException, HttpOperationFailedException {

    final HttpHead request = new HttpHead(url);
    final HttpResponse response = httpclient.execute(request);
    final int status = response.getStatusLine().getStatusCode();
    final String contentType = getContentTypeHeader(response);

    if ((status >= 200 && status < 300) || !this.throwExceptionOnFailure) {
        final HttpEntity entity = response.getEntity();
        URI describedBy = null;
        final ArrayList<URI> links = getLinkHeaders(response, "describedby");
        if (links.size() == 1) {
            describedBy = links.get(0);
        }
        return new FedoraResponse(url, status, contentType, describedBy, null);
    } else {
        throw buildHttpOperationFailedException(url, response);
    }
}

From source file:com.handsome.frame.android.volley.stack.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///w ww .  ja va  2s . c  o  m
private static HttpUriRequest createHttpRequest(Request<?> request) throws AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.GET:
        return new HttpGet(request.getUrl());
    case Request.Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Request.Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HTTP.CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Request.Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HTTP.CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Request.Method.HEAD:
        return new HttpHead(request.getUrl());
    case Request.Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Request.Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Request.Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HTTP.CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.cloudifysource.esc.shell.installer.BootstrapUrlValidator.java

private void validateUrl(final DefaultHttpClient httpClient, final String cloudifyUrl,
        final ValidationContext validationContext) throws CloudProvisioningException {

    final HttpHead httpMethod = new HttpHead(cloudifyUrl);

    try {//from   w  w w.  j av  a 2  s  .c o  m
        validationContext.validationOngoingEvent(ValidationMessageType.TOP_LEVEL_VALIDATION_MESSAGE,
                ShellUtils.getFormattedMessage(CloudifyErrorMessages.EVENT_VALIDATING_CLOUDIFY_URL.getName(),
                        cloudifyUrl));
        final HttpResponse response = httpClient.execute(httpMethod);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            validationContext.validationEventEnd(ValidationResultType.ERROR);
            logger.warning("Failed to validate Cloudify URL: " + cloudifyUrl);
            throw new CloudProvisioningException("Invalid cloudify URL: " + cloudifyUrl);
        }
        validationContext.validationEventEnd(ValidationResultType.OK);
    } catch (final ClientProtocolException e) {
        validationContext.validationOngoingEvent(ValidationMessageType.TOP_LEVEL_VALIDATION_MESSAGE,
                " Unable to validate URL");
        validationContext.validationEventEnd(ValidationResultType.WARNING);
        logger.fine("Failed to validate Cloudify URL: " + cloudifyUrl);
    } catch (final IOException e) {
        validationContext.validationOngoingEvent(ValidationMessageType.TOP_LEVEL_VALIDATION_MESSAGE,
                " Unable to validate URL");
        validationContext.validationEventEnd(ValidationResultType.WARNING);
        logger.fine("Failed to validate Cloudify URL: " + cloudifyUrl);
    }
}

From source file:org.sonatype.nexus.test.utils.hc4client.Hc4MethodCall.java

/**
 * Constructor./* w w w .  j  ava2s.com*/
 *
 * @param helper     The parent HTTP client helper.
 * @param method     The method name.
 * @param requestUri The request URI.
 * @param hasEntity  Indicates if the call will have an entity to send to the server.
 */
public Hc4MethodCall(Hc4ClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new HttpGet(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new HttpPost(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new HttpPut(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HttpHead(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new HttpDelete(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            // CONNECT unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new HttpOptions(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new HttpTrace(requestUri);
        } else {
            // custom HTTP verbs unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        }

        this.httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,
                this.clientHelper.isFollowRedirects());
        // retry handler setting unsupported (legaacy ITs use default HC4 retry handler)
        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}