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.mpower.daktar.android.utilities.WebUtils.java

public static final HttpHead createOpenRosaHttpHead(final URI uri) {
    final HttpHead req = new HttpHead(uri);
    setOpenRosaHeaders(req);//from  w  w w.jav  a  2s. c om
    return req;
}

From source file:ch.cyberduck.core.dav.DAVSession.java

@Override
public void login(final HostPasswordStore keychain, final LoginCallback prompt, final CancelCallback cancel)
        throws BackgroundException {
    client.setCredentials(host.getCredentials().getUsername(), host.getCredentials().getPassword(),
            // Windows credentials. Provide empty string for NTLM domain by default.
            preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain"));
    if (preferences.getBoolean("webdav.basic.preemptive")) {
        // Enable preemptive authentication. See HttpState#setAuthenticationPreemptive
        client.enablePreemptiveAuthentication(host.getHostname(), host.getPort(), host.getPort(),
                Charset.forName(preferences.getProperty("http.credentials.charset")));
    } else {/* www  .  j  a  v a  2s  .  c  o m*/
        client.disablePreemptiveAuthentication();
    }
    if (host.getCredentials().isPassed()) {
        log.warn(String.format(
                "Skip verifying credentials with previous successful authentication event for %s", this));
        return;
    }
    try {
        final Path home = new DefaultHomeFinderService(this).find();
        try {
            client.execute(new HttpHead(new DAVPathEncoder().encode(home)), new VoidResponseHandler());
        } catch (SardineException e) {
            switch (e.getStatusCode()) {
            case HttpStatus.SC_FORBIDDEN:
            case HttpStatus.SC_NOT_FOUND:
            case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
            case HttpStatus.SC_METHOD_NOT_ALLOWED:
                log.warn(String.format("Failed HEAD request to %s with %s. Retry with PROPFIND.", host,
                        e.getResponsePhrase()));
                cancel.verify();
                // Possibly only HEAD requests are not allowed
                this.getFeature(ListService.class).list(home, new DisabledListProgressListener() {
                    @Override
                    public void chunk(final Path parent, final AttributedList<Path> list)
                            throws ListCanceledException {
                        try {
                            cancel.verify();
                        } catch (ConnectionCanceledException e) {
                            throw new ListCanceledException(list, e);
                        }
                    }
                });
                break;
            case HttpStatus.SC_BAD_REQUEST:
                if (preferences.getBoolean("webdav.basic.preemptive")) {
                    log.warn(String.format("Disable preemptive authentication for %s due to failure %s", host,
                            e.getResponsePhrase()));
                    cancel.verify();
                    client.disablePreemptiveAuthentication();
                    client.execute(new HttpHead(new DAVPathEncoder().encode(home)), new VoidResponseHandler());
                } else {
                    throw new DAVExceptionMappingService().map(e);
                }
                break;
            default:
                throw new DAVExceptionMappingService().map(e);
            }
        }
    } catch (SardineException e) {
        throw new DAVExceptionMappingService().map(e);
    } catch (IOException e) {
        throw new HttpExceptionMappingService().map(e);
    }
}

From source file:com.addthis.hydra.task.output.HttpOutputWriter.java

private HttpUriRequest buildRequest(String requestType, String endpoint, HttpEntity entity) {
    switch (requestType) {
    case "POST":
        HttpPost post = new HttpPost(endpoint);
        post.setEntity(entity);//w  w w.  j  a  v  a2 s . c om
        return post;
    case "GET":
        return new HttpGet(endpoint);
    case "HEAD":
        return new HttpHead(endpoint);
    case "PUT":
        return new HttpPut(endpoint);
    default:
        log.error("Unsupported HTTP method: {}", requestType);
        throw new DataChannelError("Unsupported HTTP method: " + requestType);
    }
}

From source file:org.fcrepo.integration.connector.file.FileConnectorIT.java

/**
 * When I make changes to a resource in a federated filesystem, the parent folder's Last-Modified header should be
 * updated.//w  w w .  j  a  v  a 2 s. c o  m
 *
 * @throws IOException thrown during this function
 **/
@Test
public void testLastModifiedUpdatedAfterUpdates() throws IOException {
    // create directory containing a file in filesystem
    final File fed = new File("target/test-classes/test-objects");
    final String id = randomUUID().toString();
    final File dir = new File(fed, id);
    final File child = new File(dir, "child");
    final long timestamp1 = currentTimeMillis();
    dir.mkdir();
    child.mkdir();
    // TODO this seems really brittle
    try {
        sleep(2000);
    } catch (final InterruptedException e) {
    }

    // check Last-Modified header is current
    final long lastmod1;
    try (final CloseableHttpResponse resp1 = client.execute(new HttpHead(serverAddress + "files/" + id))) {
        assertEquals(OK.getStatusCode(), getStatus(resp1));
        lastmod1 = headerFormat.parse(resp1.getFirstHeader("Last-Modified").getValue()).getTime();
        assertTrue((timestamp1 - lastmod1) < 1000); // because rounding

        // remove the file and wait for the TTL to expire
        final long timestamp2 = currentTimeMillis();
        child.delete();
        try {
            sleep(2000);
        } catch (final InterruptedException e) {
        }

        // check Last-Modified header is updated
        try (final CloseableHttpResponse resp2 = client.execute(new HttpHead(serverAddress + "files/" + id))) {
            assertEquals(OK.getStatusCode(), getStatus(resp2));
            final long lastmod2 = headerFormat.parse(resp2.getFirstHeader("Last-Modified").getValue())
                    .getTime();
            assertTrue((timestamp2 - lastmod2) < 1000); // because rounding
            assertFalse("Last-Modified headers should have changed", lastmod1 == lastmod2);
        } catch (final ParseException e) {
            fail();
        }
    } catch (final ParseException e) {
        fail();
    }
}

From source file:net.sasasin.sreader.commons.util.impl.WgetHttpComponentsImpl.java

@Override
public URL getOriginalUrl() {

    // HTTP 30x???
    RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false)
            .setConnectTimeout(DEFAULT_TIMEOUT_MILLISECONDS)
            .setConnectionRequestTimeout(DEFAULT_TIMEOUT_MILLISECONDS).build();

    // UserAgent?MSIE
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));

    HttpResponse responce = null;/*  w  ww .  jav a2s  . c  o  m*/
    try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
            .setDefaultHeaders(headers).build()) {
        responce = httpclient.execute(new HttpHead(getUrl().toString()));

        int httpStatusCode = responce.getStatusLine().getStatusCode();

        if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || httpStatusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // 301,302???Location??URL??
            Header h = responce.getFirstHeader("Location");
            if (!getUrl().toString().equals(h.getValue())) {
                // URL????URL?
                return new URL(h.getValue());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 30x????????URL?
    return getUrl();
}

From source file:spaceRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else {// w  w  w . java  2s.  co m
        return new HttpGet(uri);
    }
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

/**
* does a http head request//from   www  .j ava 2  s. c  om
 * @param url
 * @param username
 * @param password
 * @param timeout
 * @param charset
 * @param useragent
 * @param proxyserver
 * @param proxyport
 * @param proxyuser
 * @param proxypassword
 * @param headers
 * @return
 * @throws IOException
 */
public static HTTPResponse head(URL url, String username, String password, long timeout, int maxRedirect,
        String charset, String useragent, ProxyData proxy, lucee.commons.net.http.Header[] headers)
        throws IOException {
    HttpHead head = new HttpHead(url.toExternalForm());
    return _invoke(url, head, username, password, timeout, maxRedirect, charset, useragent, proxy, headers,
            null);
}

From source file:com.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   ww  w  . j  ava 2  s . c o  m
 *            The request to convert to an HttpClient method object.
 * @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.
 * @throws FakeIOException only for test simulation
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        ExecutionContext context) throws FakeIOException {
    URI endpoint = request.getEndpoint();

    /*
     * HttpClient cannot handle url in pattern of "http://host//path", so we
     * have to escape the double-slash between endpoint and resource-path
     * into "/%2F"
     */
    String uri = HttpUtils.appendUri(endpoint.toString(), request.getResourcePath(), true);
    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);

        /*
         * We should never reuse the entity of the previous request, since
         * reading from the buffered entity will bypass reading from the
         * original request content. And if the content contains InputStream
         * wrappers that were added for validation-purpose (e.g.
         * Md5DigestCalculationInputStream), these wrappers would never be
         * read and updated again after AmazonHttpClient resets it in
         * preparation for the retry. Eventually, these wrappers would
         * return incorrect validation result.
         */
        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.PATCH) {
        HttpPatch patchMethod = new HttpPatch(uri);
        httpRequest = patchMethod;

        /*
         * We should never reuse the entity of the previous request, since
         * reading from the buffered entity will bypass reading from the
         * original request content. And if the content contains InputStream
         * wrappers that were added for validation-purpose (e.g.
         * Md5DigestCalculationInputStream), these wrappers would never be
         * read and updated again after AmazonHttpClient resets it in
         * preparation for the retry. Eventually, these wrappers would
         * return incorrect validation result.
         */
        if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            patchMethod.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:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

/**
 * does a http head request//from  w  w w  . j  av a2  s. c o  m
 * 
 * @param url
 * @param username
 * @param password
 * @param timeout
 * @param charset
 * @param useragent
 * @param proxyserver
 * @param proxyport
 * @param proxyuser
 * @param proxypassword
 * @param headers
 * @return
 * @throws IOException
 */
public static HTTPResponse head(URL url, String username, String password, long timeout, boolean redirect,
        String charset, String useragent, ProxyData proxy, lucee.commons.net.http.Header[] headers)
        throws IOException {
    HttpHead head = new HttpHead(url.toExternalForm());
    return _invoke(url, head, username, password, timeout, redirect, charset, useragent, proxy, headers, null);
}

From source file:leap.webunit.client.THttpRequestImpl.java

protected HttpRequestBase newRequest(String url) {
    initRequest();//from w ww  .j a  v a 2s .  co  m

    if (method.equals(Method.GET)) {
        request = new HttpGet(url);
    }

    if (method.equals(Method.POST)) {
        request = new HttpPost(url);
    }

    if (method.equals(Method.PUT)) {
        request = new HttpPut(url);
    }

    if (method.equals(Method.DELETE)) {
        request = new HttpDelete(url);
    }

    if (method.equals(Method.PATCH)) {
        request = new HttpPatch(url);
    }

    if (method.equals(Method.HEAD)) {
        request = new HttpHead(url);
    }

    if (method.equals(Method.OPTIONS)) {
        request = new HttpOptions(url);
    }

    if (null == request) {
        throw new IllegalStateException("Http method '" + method.name() + "' not supported now");
    }

    //set headers
    Header[] headerArray = headers.getAllHeaders();
    if (null != headerArray && headerArray.length > 0) {
        request.setHeaders(headerArray);
    }

    if (null != entity) {
        entityEnclosingRequest().setEntity(entity);
    }

    return request;
}