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.emc.esu.api.rest.EsuRestApiApache.java

private HttpResponse restHead(URL url, Map<String, String> headers)
        throws URISyntaxException, ClientProtocolException, IOException {
    HttpHead head = new HttpHead(url.toURI());

    setHeaders(head, headers);//from   w  ww  . j a v  a  2s  . co m

    return httpClient.execute(head);
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the {@link HttpUriRequest} implementation appropriate to
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxy} the specified
 * <code>pageRequest</code> to the <code>proxiedFileURL</code>.
 * /*from  ww  w.j  a v  a2  s  . c o m*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param proxiedFileURL The {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}.
 * @return The created {@link HttpUriRequest}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient)
 * @see #PROXY_REQUEST_OBJ_HOOK
 */
protected HttpRequestBase createProxyRequestObject(final Page.Request pageRequest, final Mode mode,
        final URL proxiedFileURL) throws WWWEEEPortal.Exception, WebApplicationException {
    final RequestConfig requestConfig = createProxyClientRequestConfig(pageRequest, mode);

    final Object[] context = new Object[] { mode, proxiedFileURL, requestConfig };
    HttpRequestBase proxyRequest = PROXY_REQUEST_OBJ_HOOK.value(plugins, context, pageRequest);
    if (proxyRequest == null) {

        final URI proxiedFileURI;
        try {
            proxiedFileURI = proxiedFileURL.toURI();
        } catch (URISyntaxException urise) {
            throw new WWWEEEPortal.SoftwareException(urise);
        }

        final String method = pageRequest.getRSRequest().getMethod();
        if ((!pageRequest.isMaximized(this)) || (method.equalsIgnoreCase("GET"))) {
            proxyRequest = new HttpGet(proxiedFileURI);
        } else if (method.equalsIgnoreCase("HEAD")) {
            proxyRequest = new HttpHead(proxiedFileURI);
        } else if (method.equalsIgnoreCase("POST")) {
            proxyRequest = new HttpPost(proxiedFileURI);
        } else if (method.equalsIgnoreCase("PUT")) {
            proxyRequest = new HttpPut(proxiedFileURI);
        } else if (method.equalsIgnoreCase("DELETE")) {
            proxyRequest = new HttpDelete(proxiedFileURI);
        } else {
            throw new WebApplicationException(
                    Response.status(RESTUtil.Response.Status.METHOD_NOT_ALLOWED).build());
        }

        proxyRequest.setConfig(requestConfig);

    }
    proxyRequest = PROXY_REQUEST_OBJ_HOOK
            .requireFilteredResult(PROXY_REQUEST_OBJ_HOOK.filter(plugins, context, pageRequest, proxyRequest));
    return proxyRequest;
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * // w w w. j  a  va  2 s .  c o m
 * 
 * @param container
 *             
 * @param objName
 *             
 * @return 
 * 
 * @throws IOException
 *              IO
 * @throws HttpException
 *              Http
 * @throws FilesAuthorizationException
 *              
 * @throws FilesInvalidNameException
 *              
 * @throws FilesNotFoundException
 *              
 */
public FilesObjectMetaData getObjectMetaData(String container, String objName) throws IOException,
        FilesNotFoundException, HttpException, FilesAuthorizationException, FilesInvalidNameException {
    FilesObjectMetaData metaData;
    if (this.isLoggedin()) {
        if (isValidContainerName(container) && isValidObjectName(objName)) {
            HttpHead method = new HttpHead(
                    storageURL + "/" + sanitizeForURI(container) + "/" + sanitizeForURI(objName));
            try {
                method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                FilesResponse response = new FilesResponse(client.execute(method));

                if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    method.abort();
                    login();
                    method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                    method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                    response = new FilesResponse(client.execute(method));
                }

                if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT
                        || response.getStatusCode() == HttpStatus.SC_OK) {
                    logger.debug("Object metadata retreived  : " + objName);
                    String mimeType = response.getContentType();
                    String lastModified = response.getLastModified();
                    String eTag = response.getETag();
                    String contentLength = response.getContentLength();

                    metaData = new FilesObjectMetaData(mimeType, contentLength, eTag, lastModified);

                    Header[] headers = response.getResponseHeaders();
                    HashMap<String, String> headerMap = new HashMap<String, String>();

                    for (Header h : headers) {
                        if (h.getName().startsWith(FilesConstants.X_OBJECT_META)) {
                            headerMap.put(h.getName().substring(FilesConstants.X_OBJECT_META.length()),
                                    unencodeURI(h.getValue()));
                        }
                    }
                    if (headerMap.size() > 0)
                        metaData.setMetaData(headerMap);

                    return metaData;
                } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                    throw new FilesNotFoundException(
                            "Container: " + container + " did not have object " + objName,
                            response.getResponseHeaders(), response.getStatusLine());
                } else {
                    throw new FilesException("Unexpected Return Code from Server",
                            response.getResponseHeaders(), response.getStatusLine());
                }
            } finally {
                method.abort();
            }
        } else {
            if (!isValidObjectName(objName)) {
                throw new FilesInvalidNameException(objName);
            } else {
                throw new FilesInvalidNameException(container);
            }
        }
    } else {
        throw new FilesAuthorizationException("You must be logged in", null, null);
    }
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

private SS3Object getObjectWithSignedUrlImpl(String signedGetOrHeadUrl, boolean headOnly)
        throws ServiceException {
    String s3Endpoint = this.getEndpoint();

    HttpRequestBase httpMethod = null;//from   w  w w. j a v  a  2  s  .co m
    if (headOnly) {
        httpMethod = new HttpHead(signedGetOrHeadUrl);
    } else {
        httpMethod = new HttpGet(signedGetOrHeadUrl);
    }

    HttpResponse httpResponse = performRequest(httpMethod, new int[] { 200 });

    Map<String, Object> map = new HashMap<String, Object>();
    map.putAll(convertHeadersToMap(httpResponse.getAllHeaders()));

    SS3Object responseObject = null;
    try {
        responseObject = ServiceUtils.buildObjectFromUrl(httpMethod.getURI().getHost(),
                httpMethod.getURI().getRawPath().substring(1), s3Endpoint);
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException("Unable to determine name of object created with signed PUT", e);
    }

    responseObject.replaceAllMetadata(
            ServiceUtils.cleanRestMetadataMap(map, this.getRestHeaderPrefix(), this.getRestMetadataPrefix()));
    responseObject.setMetadataComplete(true); // Flag this object as having the complete metadata set.
    if (!headOnly) {
        HttpMethodReleaseInputStream releaseIS = new HttpMethodReleaseInputStream(httpResponse);
        responseObject.setDataInputStream(releaseIS);
    } else {
        // Release connection after HEAD (there's no response content)
        if (log.isDebugEnabled()) {
            log.debug("Releasing HttpMethod after HEAD");
        }
        releaseConnection(httpResponse);
    }

    return responseObject;
}

From source file:netinf.node.chunking.ChunkedBO.java

private boolean providesRanges(String url) {
    HttpClient client = new DefaultHttpClient();
    try {//from  ww  w. ja  va 2  s.c om
        HttpHead httpHead = new HttpHead(url);
        httpHead.setHeader("Range", "bytes=0-");
        try {
            HttpResponse response = client.execute(httpHead);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_PARTIAL_CONTENT || status == HttpStatus.SC_OK) {
                return true;
            }
        } catch (ClientProtocolException e) {
            LOG.debug(e.getMessage());
        } catch (IOException e) {
            LOG.debug(e.getMessage());
        }
    } catch (IllegalArgumentException e) {
        LOG.debug(e.getMessage());
    }
    return false;
}

From source file:org.apache.cloudstack.storage.test.TestHttp.java

@Test
@Parameters("template-url")
public void testHttpclient(String templateUrl) {
    HttpHead method = new HttpHead(templateUrl);
    DefaultHttpClient client = new DefaultHttpClient();

    OutputStream output = null;// ww  w .j a va  2  s  . co  m
    long length = 0;
    try {
        HttpResponse response = client.execute(method);
        length = Long.parseLong(response.getFirstHeader("Content-Length").getValue());
        System.out.println(response.getFirstHeader("Content-Length").getValue());
        File localFile = new File("/tmp/test");
        if (!localFile.exists()) {
            localFile.createNewFile();
        }

        HttpGet getMethod = new HttpGet(templateUrl);
        response = client.execute(getMethod);
        HttpEntity entity = response.getEntity();

        output = new BufferedOutputStream(new FileOutputStream(localFile));
        entity.writeTo(output);
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (output != null)
                output.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    File f = new File("/tmp/test");
    Assert.assertEquals(f.length(), length);
}

From source file:org.apache.http.impl.client.DefaultRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    final URI uri = getLocationURI(request, response, context);
    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else {/*from   w ww .j a  v a 2  s .c  o  m*/
        final int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            return RequestBuilder.copy(request).setUri(uri).build();
        } else {
            return new HttpGet(uri);
        }
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + url.toString());
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }//from  w w w  .java 2s  . co m

    HTTPSampleResult res = createSampleResult(url, method);

    HttpClient httpClient = setupClient(url, res);

    HttpRequestBase httpRequest = null;
    try {
        URI uri = url.toURI();
        if (method.equals(HTTPConstants.POST)) {
            httpRequest = new HttpPost(uri);
        } else if (method.equals(HTTPConstants.GET)) {
            httpRequest = new HttpGet(uri);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpRequest = new HttpPut(uri);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpRequest = new HttpHead(uri);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpRequest = new HttpTrace(uri);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpRequest = new HttpOptions(uri);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpRequest = new HttpDelete(uri);
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpRequest = new HttpPatch(uri);
        } else if (HttpWebdav.isWebdavMethod(method)) {
            httpRequest = new HttpWebdav(method, uri);
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }
        setupRequest(url, httpRequest, res); // can throw IOException
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }

    HttpContext localContext = new BasicHttpContext();
    setupClientContextBeforeSample(localContext);

    res.sampleStart();

    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }

    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(SAMPLER_RESULT_TOKEN, res);
        // perform the sample
        HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url);

        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        extractClientContextAfterSample(localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = (InetAddress) httpRequest.getParams()
                .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
        if (localAddr != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        res.setRequestHeaders(getConnectionHeaders(request));

        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength()));
        }

        res.sampleEnd(); // Done with the sampling proper.
        currentRequest = null;

        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseHeaders(getResponseHeaders(httpResponse, localContext));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException(
                        "Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
        long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
                + httpResponse.getAllHeaders().length // Add \r for each header
                + 1 // Add \r for initial header
                + 2; // final \r\n before data
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize((int) (totalBytes - headerBytes));
        if (log.isDebugEnabled()) {
            log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: " + res.getRequestHeaders());
        }
        res.setRequestHeaders(
                getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN);
    }
    return res;
}