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:ch.cyberduck.core.dav.DAVAttributesFinderFeature.java

@Override
public PathAttributes find(final Path file) throws BackgroundException {
    if (file.isRoot()) {
        return PathAttributes.EMPTY;
    }/*from  www .  j  av  a2  s.c o  m*/
    try {
        try {
            final List<DavResource> status = session.getClient().list(new DAVPathEncoder().encode(file), 1,
                    Collections.<QName>emptySet());
            for (final DavResource resource : status) {
                if (resource.isDirectory()) {
                    if (!file.getType().contains(Path.Type.directory)) {
                        throw new NotfoundException(String.format("Path %s is directory", file.getAbsolute()));
                    }
                } else {
                    if (!file.getType().contains(Path.Type.file)) {
                        throw new NotfoundException(String.format("Path %s is file", file.getAbsolute()));
                    }
                }
                final PathAttributes attributes = new PathAttributes();
                if (resource.getModified() != null) {
                    attributes.setModificationDate(resource.getModified().getTime());
                }
                if (resource.getCreation() != null) {
                    attributes.setCreationDate(resource.getCreation().getTime());
                }
                if (resource.getContentLength() != null) {
                    attributes.setSize(resource.getContentLength());
                }
                if (StringUtils.isNotBlank(resource.getEtag())) {
                    attributes.setETag(resource.getEtag());
                    // Setting checksum is disabled. See #8798
                    // attributes.setChecksum(Checksum.parse(resource.getEtag()));
                }
                if (StringUtils.isNotBlank(resource.getDisplayName())) {
                    attributes.setDisplayname(resource.getDisplayName());
                }
                if (StringUtils.isNotBlank(resource.getDisplayName())) {
                    attributes.setDisplayname(resource.getDisplayName());
                }
                return attributes;
            }
            throw new NotfoundException(file.getAbsolute());
        } catch (SardineException e) {
            try {
                throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, file);
            } catch (InteroperabilityException i) {
                // PROPFIND Method not allowed
                log.warn(String.format("Failure with PROPFIND request for %s. %s", file, i.getMessage()));
                final Map<String, String> headers = session.getClient()
                        .execute(new HttpHead(new DAVPathEncoder().encode(file)), new HeadersResponseHandler());
                final PathAttributes attributes = new PathAttributes();
                try {
                    attributes.setModificationDate(
                            dateParser.parse(headers.get(HttpHeaders.LAST_MODIFIED)).getTime());
                } catch (InvalidDateException p) {
                    log.warn(String.format("%s is not RFC 1123 format %s",
                            headers.get(HttpHeaders.LAST_MODIFIED), p.getMessage()));
                }
                if (!headers.containsKey(HttpHeaders.CONTENT_ENCODING)) {
                    // Set size unless response is compressed
                    attributes.setSize(NumberUtils.toLong(headers.get(HttpHeaders.CONTENT_LENGTH), -1));
                }
                if (headers.containsKey(HttpHeaders.ETAG)) {
                    attributes.setETag(headers.get(HttpHeaders.ETAG));
                    // Setting checksum is disabled. See #8798
                    // attributes.setChecksum(Checksum.parse(headers.get(HttpHeaders.ETAG)));
                }
                if (headers.containsKey(HttpHeaders.CONTENT_MD5)) {
                    attributes.setChecksum(Checksum.parse(headers.get(HttpHeaders.CONTENT_MD5)));
                }
                return attributes;
            }
        }
    } catch (SardineException e) {
        throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, file);
    } catch (IOException e) {
        throw new HttpExceptionMappingService().map(e, file);
    }
}

From source file:com.farru.android.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 */// w  ww  .j ava2 s.  com
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    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(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_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(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.codehaus.httpcache4j.resolver.HTTPClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI.//from w w  w .j  a v a2  s.  c  o m
 * @return a new HttpMethod subclass.
 */
protected HttpUriRequest getMethod(HTTPMethod method, URI requestURI) {

    if (DELETE.equals(method)) {
        return new HttpDelete(requestURI);
    } else if (GET.equals(method)) {
        return new HttpGet(requestURI);
    } else if (HEAD.equals(method)) {
        return new HttpHead(requestURI);
    } else if (OPTIONS.equals(method)) {
        return new HttpOptions(requestURI);
    } else if (POST.equals(method)) {
        return new HttpPost(requestURI);
    } else if (PUT.equals(method)) {
        return new HttpPut(requestURI);
    } else if (TRACE.equals(method)) {
        return new HttpTrace(requestURI);
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
}

From source file:at.diamonddogs.net.WebClientDefaultHttpClient.java

@Override
public ReplyAdapter call() {
    ReplyAdapter listenerReply = null;/* w w  w . j  av a  2s. c om*/
    HttpResponse response = null;
    try {
        WebReply reply;

        if (webRequest == null) {
            throw new WebClientException("WebRequest must not be null!");
        }

        if (webRequest.getRequestType() == Type.GET) {
            requestBase = new HttpGet(webRequest.getUrl().toURI());
        } else if (webRequest.getRequestType() == Type.HEAD) {
            requestBase = new HttpHead(webRequest.getUrl().toURI());
        } else if (webRequest.getRequestType() == Type.POST) {
            HttpPost post = new HttpPost(webRequest.getUrl().toURI());

            // we need to remove the content length header, to prevent
            // httpClient.execute(...) from failing
            if (webRequest.getHeader() != null) {
                webRequest.removeHeaderField("Content-Length");
            }

            handlePostParameters(post);

            requestBase = post;
        }

        configureConnection();

        LOGGER.info("Running RequestBase: " + requestBase);
        response = httpClient.execute(requestBase);
        reply = runRequest(response);

        listenerReply = createListenerReply(webRequest, reply, null, Status.OK);
    } catch (Throwable tr) {
        // TODO: passing a null reply will cause an nullpointer when calling
        // cacheObjectToFile
        listenerReply = createListenerReply(webRequest, null, tr, Status.FAILED);
        LOGGER.info("Error running webrequest: " + webRequest.getUrl() + " status: "
                + (response == null ? "" : response.getStatusLine().getStatusCode()), tr);
    }
    if (webClientReplyListener != null) {
        webClientReplyListener.onWebReply(this, listenerReply);
    }
    return listenerReply;
}

From source file:net.orpiske.ssps.common.resource.HttpResourceExchange.java

public ResourceInfo info(URI uri) throws ResourceExchangeException {
    HttpHead httpHead = new HttpHead(uri);
    HttpResponse response;/*  ww w.  j a  va 2 s . co m*/
    try {
        response = httpClient.execute(httpHead);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            long length = getContentLength(response);
            logger.debug("Reading " + length + " bytes from the server");

            ResourceInfo ret = new ResourceInfo();

            ret.setSize(length);
            ret.setLastModified(getLastModified(response));

            return ret;
        } else {
            switch (statusCode) {
            case HttpStatus.SC_NOT_FOUND:
                throw new ResourceExchangeException("Remote file not found");
            case HttpStatus.SC_BAD_REQUEST:
                throw new ResourceExchangeException("The client sent a bad request");
            case HttpStatus.SC_FORBIDDEN:
                throw new ResourceExchangeException("Accessing the resource is forbidden");
            case HttpStatus.SC_UNAUTHORIZED:
                throw new ResourceExchangeException("Unauthorized");
            case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                throw new ResourceExchangeException("Internal server error");
            default:
                throw new ResourceExchangeException("Unable to download file: http status code " + statusCode);
            }
        }
    } catch (ClientProtocolException e) {
        throw new ResourceExchangeException("Unhandled protocol error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ResourceExchangeException("I/O error: " + e.getMessage(), e);
    }
}

From source file:com.sogeti.droidnetworking.NetworkOperation.java

private int prepareRequest() {
    if (urlString == null || httpMethod == null) {
        return -1;
    }//w  ww  .  ja v a2 s.c o  m

    switch (httpMethod) {
    case GET:
        request = new HttpGet(urlString);
        break;
    case POST:
        request = new HttpPost(urlString);
        break;
    case PUT:
        request = new HttpPut(urlString);
        break;
    case DELETE:
        request = new HttpDelete(urlString);
        break;
    case HEAD:
        request = new HttpHead(urlString);
        break;
    default:
        break;
    }

    if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        for (String param : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(param, params.get(param)));
        }

        try {
            if (httpMethod == HttpMethod.POST) {
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } else {
                ((HttpPut) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    if (useGzip) {
        this.headers.put("Accept-Encoding", "gzip");
    }

    for (String header : headers.keySet()) {
        request.addHeader(header, headers.get(header));
    }

    return 0;
}

From source file:org.apache.jena.web.DatasetGraphAccessorHTTP.java

protected boolean doHead(String url) {
    HttpUriRequest httpHead = new HttpHead(url);
    try {//  www.ja v  a  2s  .  c  o m
        HttpOp.execHttpHead(url, WebContent.defaultGraphAcceptHeader, noResponse, null, null,
                this.authenticator);
        return true;
    } catch (HttpException ex) {
        if (ex.getResponseCode() == HttpSC.NOT_FOUND_404)
            return false;
        throw ex;
    }
}

From source file:org.bedework.util.http.HttpUtil.java

/** Specify the next method by name.
 *
 * @param name of the method/*from  ww  w .  j a  v  a  2  s .c om*/
 * @param uri target
 * @return method object or null for unknown
 */
public static HttpRequestBase findMethod(final String name, final URI uri) {
    final String nm = name.toUpperCase();

    if ("PUT".equals(nm)) {
        return new HttpPut(uri);
    }

    if ("GET".equals(nm)) {
        return new HttpGet(uri);
    }

    if ("DELETE".equals(nm)) {
        return new HttpDelete(uri);
    }

    if ("POST".equals(nm)) {
        return new HttpPost(uri);
    }

    if ("PROPFIND".equals(nm)) {
        return new HttpPropfind(uri);
    }

    if ("MKCALENDAR".equals(nm)) {
        return new HttpMkcalendar(uri);
    }

    if ("MKCOL".equals(nm)) {
        return new HttpMkcol(uri);
    }

    if ("OPTIONS".equals(nm)) {
        return new HttpOptions(uri);
    }

    if ("REPORT".equals(nm)) {
        return new HttpReport(uri);
    }

    if ("HEAD".equals(nm)) {
        return new HttpHead(uri);
    }

    return null;
}

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

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

    HttpRequestBase internalRequest;//from  ww w  .j av a  2s .co m
    if (request.method == HttpMethod.HEAD) {
        internalRequest = new HttpHead(uri);
    } else {
        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:com.joyent.manta.http.MantaHttpRequestFactory.java

/**
 * Convenience method used for building HEAD operations.
 * @param path path to resource//  w ww  .  jav a  2 s.  c o m
 * @return instance of configured {@link org.apache.http.client.methods.HttpRequestBase} object.
 */
public HttpHead head(final String path) {
    final HttpHead request = new HttpHead(uriForPath(path));
    prepare(request);
    return request;
}