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:cn.edu.zzu.wemall.http.AsyncHttpClient.java

/**
 * Perform a HTTP HEAD request and track the Android Context which initiated
 * the request with customized headers/*from  w  w  w . j  ava2 s. c om*/
 *
 * @param context         Context to execute request against
 * @param url             the URL to send the request to.
 * @param headers         set headers only for this request
 * @param params          additional HEAD parameters to send with the request.
 * @param responseHandler the response handler instance that should handle
 *                        the response.
 */
public RequestHandle head(Context context, String url, Header[] headers, RequestParams params,
        AsyncHttpResponseHandler responseHandler) {
    HttpUriRequest request = new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params));
    if (headers != null)
        request.setHeaders(headers);
    return sendRequest(httpClient, httpContext, request, null, responseHandler, context);
}

From source file:org.apache.sling.testing.clients.AbstractSlingClient.java

/**
 * <p>Executes a HEAD request</p>
 *
 * <p>Adds the passed parameters and headers and checks the expected status</p>
 *
 * @param requestPath path relative to client url
 * @param parameters optional url parameters to be added
 * @param headers optional headers to be added
 * @param expectedStatus if passed, the response status will have to match one of them
 * @return the response//from www  .  j  av a2s.c om
 * @throws ClientException if the request could not be executed
 */
public SlingHttpResponse doHead(String requestPath, List<NameValuePair> parameters, List<Header> headers,
        int... expectedStatus) throws ClientException {
    HttpUriRequest request = new HttpHead(getUrl(requestPath, parameters));
    return doRequest(request, headers, expectedStatus);
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected HttpResponse executeHeadRequest(final String request, Header... header) throws Exception {
    return executeRequest(new HttpHead(getHttpServerUri() + "/" + request), header);
}

From source file:com.microsoft.azure.management.resources.DeploymentOperationsImpl.java

/**
* Checks whether deployment exists./*from   w  ww.  j a  va 2  s. c o  m*/
*
* @param resourceGroupName Required. The name of the resource group to
* check. The name is case insensitive.
* @param deploymentName Required. The name of the deployment.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Deployment information.
*/
@Override
public DeploymentExistsResult checkExistence(String resourceGroupName, String deploymentName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("deploymentName", deploymentName);
        CloudTracing.enter(invocationId, this, "checkExistenceAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourcegroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01-preview");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpHead httpRequest = new HttpHead(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_NOT_FOUND) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DeploymentExistsResult result = null;
        // Deserialize Response
        result = new DeploymentExistsResult();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_NO_CONTENT) {
            result.setExists(true);
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * This method gets HEAD response/*from  w ww  . ja va  2s.com*/
 *
 * @param url the url to Response from
 * @return the HttpResponse
 * @throws IOException
 */
public HttpResponse HEADResponse(final MultiProtocolURL url, final boolean concurrent) throws IOException {
    final HttpHead httpHead = new HttpHead(url.toNormalform(true));
    setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service
    execute(httpHead, concurrent);
    finish();
    ConnectionInfo.removeConnection(httpHead.hashCode());
    return this.httpResponse;
}

From source file:com.iflytek.cssp.SwiftAPI.SwiftClient.java

public SwiftClientResponse HeadObject(String url, String Container, String object_name, String accesskey,
        String secretkey) throws IOException, CSSPException {
    Map<String, String> headers = new LinkedHashMap<String, String>();
    BasicHttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpHead httphead = new HttpHead(url + "/" + encode(Container) + "/" + encode(object_name));

    CSSPSignature signature = new CSSPSignature("HEAD", null, "/" + Container + "/" + object_name, null, null);
    signature.getDate();/*from   w ww.  ja v a2s  .c  o m*/
    String auth = signature.getSinature();
    String signa = signature.HmacSHA1Encrypt(auth, secretkey);

    httphead.addHeader(DATE, signature.Date);
    httphead.addHeader(AUTH, CSSP + accesskey + ":" + signa);
    HttpResponse response = httpClient.execute(httphead);
    Header[] Headers = response.getAllHeaders();
    for (Header Header : Headers) {
        headers.put(Header.getName(), Header.getValue());
    }
    if (isMatch_2XX(response.getStatusLine().getStatusCode()))//2xx 401
    {
        return new SwiftClientResponse(headers, response.getStatusLine().getStatusCode(),
                response.getStatusLine(), null, null);
    } else {
        logger.error(
                "[get metadata for object: error,  StatusCode is ]" + response.getStatusLine().getStatusCode());
        return new ExceptionHandle().ObjectExceptionHandle(response, headers);
    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected @Nullable Map<String, String> head(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource) throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".head(" + authToken + "," + endpoint + ","
                + resource + ")");
    }//  www .  j a v a  2s . c  o  m
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpHead head = new HttpHead(endpoint + resource);

        head.addHeader("X-Auth-Token", authToken);

        if (wire.isDebugEnabled()) {
            wire.debug(head.getRequestLine().toString());
            for (Header header : head.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(head);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code != HttpServletResponse.SC_NO_CONTENT && code != HttpServletResponse.SC_OK) {
            if (code == HttpServletResponse.SC_NOT_FOUND) {
                return null;
            }
            std.error("head(): Expected NO CONTENT or OK for HEAD request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                return null;
            }
            std.error("head(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        }
        HashMap<String, String> map = new HashMap<String, String>();

        for (Header h : response.getAllHeaders()) {
            map.put(h.getName().trim(), h.getValue().trim());
        }
        return map;
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".head()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + resource);
        }
    }
}

From source file:com.enjoy.nerd.http.AsyncHttpClient.java

/**
 * Perform a HTTP HEAD request and track the Android Context which initiated the request.
 *
 * @param context         the Android Context which initiated the request.
 * @param url             the URL to send the request to.
 * @param params          additional HEAD parameters to send with the request.
 * @param responseHandler the response handler instance that should handle the response.
 * @return RequestHandle of future request process
 *///from w  ww.  j av a 2s . c o  m
public RequestHandle head(Context context, String url, RequestParams params,
        ResponseHandlerInterface responseHandler) {
    SyncBasicHttpContext httpContext = new SyncBasicHttpContext(mBasicHttpContext);
    return sendRequest(httpClient, httpContext,
            new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params)), null, responseHandler,
            context);
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.SteeringTest.java

License:asdf

@Test
public void itUsesNoMultiLocationFormatResponseWithHead() throws Exception {
    final List<String> paths = new ArrayList<String>();
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=true");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=TRUE");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=TruE");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=T");

    for (final String path : paths) {
        HttpHead httpHead = new HttpHead("http://localhost:" + routerHttpPort + path);
        httpHead.addHeader("Host", "tr.client-steering-test-1.thecdn.example.com");

        CloseableHttpResponse response = null;

        try {/*ww  w.ja  v  a 2  s .  com*/
            response = httpClient.execute(httpHead);
            String location = ".client-steering-target-2.thecdn.example.com:8090" + path;

            assertThat("Failed getting 302 for request " + httpHead.getFirstHeader("Host").getValue(),
                    response.getStatusLine().getStatusCode(), equalTo(302));
            assertThat(response.getFirstHeader("Location").getValue(), endsWith(location));
            assertThat("Failed getting null body for HEAD request", response.getEntity(), nullValue());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}