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.jaeksoft.searchlib.crawler.web.spider.HttpDownloader.java

public final DownloadItem request(final URI uri, final Method method, final CredentialItem credentialItem,
        final List<Header> additionalHeaders, final List<CookieItem> cookies, final HttpEntity entity)
        throws ClientProtocolException, IllegalStateException, IOException, URISyntaxException,
        SearchLibException {/*  w w  w. j  ava  2s .  c o m*/
    HttpRequestBase httpRequestBase;
    switch (method) {
    case GET:
        httpRequestBase = new HttpGet(uri);
        break;
    case POST:
        httpRequestBase = new HttpPost(uri);
        break;
    case PUT:
        httpRequestBase = new HttpPut(uri);
        break;
    case DELETE:
        httpRequestBase = new HttpDelete(uri);
        break;
    case OPTIONS:
        httpRequestBase = new HttpOptions(uri);
        break;
    case PATCH:
        httpRequestBase = new HttpPatch(uri);
        break;
    case HEAD:
        httpRequestBase = new HttpHead(uri);
        break;
    default:
        throw new SearchLibException("Unkown method: " + method);
    }
    return request(httpRequestBase, credentialItem, additionalHeaders, cookies, entity);
}

From source file:com.joyent.manta.http.MantaHttpRequestFactory.java

/**
 * Convenience method used for building HEAD operations.
 * @param path path to resource/*from w  w w .ja  v a  2 s.co  m*/
 * @param params list of query parameters to use in operation
 * @return instance of configured {@link org.apache.http.client.methods.HttpRequestBase} object.
 */
public HttpHead head(final String path, final List<NameValuePair> params) {
    final HttpHead request = new HttpHead(uriForPath(path, params));
    prepare(request);
    return request;
}

From source file:com.github.technosf.posterer.modules.commons.transport.CommonsResponseModelTaskImpl.java

/**
 * Generates the specific request type/* w w  w. ja  v a  2 s .c o  m*/
 * 
 * @param uri
 *            the uri
 * @param method
 *            the request method
 * @return the request
 */
@Nullable
private static HttpUriRequest createRequest(final @Nullable URI uri, final @Nullable String method) {
    if (method != null && uri != null) {
        switch (method) {
        case "GET":
            return new HttpGet(uri);
        case "HEAD":
            return new HttpHead(uri);
        case "POST":
            return new HttpPost(uri);
        case "PUT":
            return new HttpPut(uri);
        case "DELETE":
            return new HttpDelete(uri);
        case "TRACE":
            return new HttpTrace(uri);
        case "OPTIONS":
            return new HttpOptions(uri);
        case "PATCH":
            return new HttpPatch(uri);
        }
    }

    LOG.error(CONST_ERR_UNKNOWN_METHOD, method);
    return null;
}

From source file:org.asqatasun.util.http.HttpRequestHandler.java

public int getHttpStatus(String url) throws IOException {
    String encodedUrl = getEncodedUrl(url);
    CloseableHttpClient httpClient = getHttpClient(encodedUrl);
    HttpHead head = new HttpHead(encodedUrl);
    try {//from w  w w. java2 s  . com
        LOGGER.debug("executing head request to retrieve page status on " + head.getURI());
        HttpResponse response = httpClient.execute(head);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("received " + response.getStatusLine().getStatusCode() + " from head request");
            for (Header h : head.getAllHeaders()) {
                LOGGER.debug("header : " + h.getName() + " " + h.getValue());
            }
        }

        return response.getStatusLine().getStatusCode();
    } catch (UnknownHostException uhe) {
        LOGGER.warn("UnknownHostException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IllegalArgumentException iae) {
        LOGGER.warn("IllegalArgumentException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IOException ioe) {
        LOGGER.warn("IOException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        head.releaseConnection();
        httpClient.close();
    }
}

From source file:org.commonjava.aprox.autoprox.data.AutoProxDataManagerDecorator.java

/**
 * Validates the remote connection, produced from rule-set for given name, 
 * for a remote repo or group containing a remote. If:
 * // ww w . ja  v a  2 s.co m
 * <ul>
 *   <li>rule.isValidationEnabled() == false, return true</li>
 *   <li>rule.getValidationRemote() == null, return true</li>
 *   <li>
 *     rule.getRemoteValidationPath() != null, validate remote.getUrl() + validationPath
 *     <ul>
 *       <li>if response code is 200 OK, then return true</li>
 *       <li>otherwise, return false</li>
 *     </ul>
 *   </li>
 * </ul>
 * @throws AproxDataException if the selected rule encounters an error while creating the new group/repository instance(s).
 */
private boolean checkValidity(final String name) throws AproxDataException {
    if (catalog.isValidationEnabled(name)) {
        try {
            final RemoteRepository validationRepo = catalog.createValidationRemote(name);
            if (validationRepo == null) {
                return true;
            }

            String url = catalog.getRemoteValidationUrl(name);
            if (url == null) {
                url = validationRepo.getUrl();
            } else {
                url = normalize(validationRepo.getUrl(), url);
            }

            logger.debug("\n\n\n\n\n[AutoProx] Checking URL: {}", url);
            final HttpHead head = new HttpHead(url);

            http.bindRepositoryCredentialsTo(validationRepo, head);

            boolean result = false;
            try {
                final HttpResponse response = http.getClient().execute(head);
                final StatusLine statusLine = response.getStatusLine();
                final int status = statusLine.getStatusCode();
                logger.debug("[AutoProx] HTTP Status: {}", statusLine);
                result = status == HttpStatus.SC_OK;

                if (!result) {
                    logger.warn("Invalid repository URL: {}", validationRepo.getUrl());
                }
            } catch (final ClientProtocolException e) {
                logger.warn("[AutoProx] Cannot connect to target repository: '{}'.", url);
            } catch (final IOException e) {
                logger.warn("[AutoProx] Cannot connect to target repository: '{}'.", url);
            } finally {
                head.reset();

                http.clearRepositoryCredentials();
                http.closeConnection();
            }

            return result;
        } catch (final AutoProxRuleException e) {
            throw new AproxDataException(
                    "[AUTOPROX] Failed to create new group from factory matching: '%s'. Reason: %s", e, name,
                    e.getMessage());
        }
    }

    return true;
}

From source file:org.lokra.seaweedfs.core.VolumeWrapper.java

/**
 * Get file status.//from  ww w.  j  a  v  a  2s  .  c  o m
 *
 * @param url Server url.
 * @param fid File id.
 * @return File status header.
 * @throws IOException Http connection is fail or server response within some error message.
 */
HeaderResponse getFileStatusHeader(String url, String fid) throws IOException {
    HttpHead request = new HttpHead(url + "/" + fid);
    HeaderResponse cache = connection.fetchHeaderByRequest(request);
    convertResponseStatusToException(cache.getHttpResponseStatusCode(), url, fid, false, false, false, false);
    return cache;
}

From source file:pt.lunacloud.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request//  www  . j  ava2s .  c o m
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 *
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();
    String uri = endpoint.toString();
    if (request.getResourcePath() != null && request.getResourcePath().length() > 0) {
        if (request.getResourcePath().startsWith("/")) {
            if (uri.endsWith("/")) {
                uri = uri.substring(0, uri.length() - 1);
            }
        } else if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += request.getResourcePath();
    } else if (!uri.endsWith("/")) {
        uri += "/";
    }

    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * 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.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new LunacloudClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}

From source file:com.amazon.s3.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 * /* w w  w.ja  v  a 2s.  c  o m*/
 * @param request
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 * 
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();
    String uri = endpoint.toString();
    if (request.getResourcePath() != null && request.getResourcePath().length() > 0) {
        if (request.getResourcePath().startsWith("/")) {
            if (uri.endsWith("/")) {
                uri = uri.substring(0, uri.length() - 1);
            }
        } else if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += request.getResourcePath();
    } else if (!uri.endsWith("/")) {
        uri += "/";
    }

    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * 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.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new AmazonClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}

From source file:cn.ctyun.amazonaws.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request/*from  w w w.j  a v  a  2 s . com*/
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 *
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();
    String uri = endpoint.toString();
    if (request.getResourcePath() != null && request.getResourcePath().length() > 0) {
        if (request.getResourcePath().startsWith("/")) {
            if (uri.endsWith("/")) {
                uri = uri.substring(0, uri.length() - 1);
            }
        } else if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += HttpUtils.urlEncode(request.getResourcePath(), true);
    } else if (!uri.endsWith("/")) {
        uri += "/";
    }

    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * 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.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new AmazonClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}