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:org.seasar.robot.client.http.HcHttpClient.java

@Override
public ResponseData doHead(final String url) {
    HttpUriRequest httpHead;// w w  w. j  av a  2  s .c om
    try {
        httpHead = new HttpHead(url);
    } catch (final IllegalArgumentException e) {
        throw new RobotCrawlAccessException("The url may not be valid: " + url, e);
    }
    return doHttpMethod(url, httpHead);
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Creates HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the internal request.
 *
 * @param request The request to convert to an HttpClient method object.
 * @return The converted HttpClient method object with any parameters, headers, etc. from the original request set.
 *///from w w  w. ja  va  2 s .  c  o m
protected HttpRequestBase createHttpRequest(InternalRequest request) {
    String uri = request.getUri().toASCIIString();
    String encodedParams = HttpUtils.getCanonicalQueryString(request.getParameters(), false);

    if (encodedParams.length() > 0) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    long contentLength = -1;
    String contentLengthString = request.getHeaders().get(Headers.CONTENT_LENGTH);
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
    }
    if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;
        if (request.getContent() != null) {
            putMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength));
        }
    } else if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);
        httpRequest = postMethod;
        if (request.getContent() != null) {
            postMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength));
        }
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new BceClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    httpRequest.addHeader(Headers.HOST, HttpUtils.generateHostHeader(request.getUri()));

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : request.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if it's already present, so we skip it here.
         * We also skip the Host header to avoid sending it twice, which will interfere with some signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase(Headers.CONTENT_LENGTH)
                || entry.getKey().equalsIgnoreCase(Headers.HOST)) {
            continue;
        }

        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    checkNotNull(httpRequest.getFirstHeader(Headers.CONTENT_TYPE), Headers.CONTENT_TYPE + " not set");
    return httpRequest;
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/*************************** all request methods ******************/

public HttpResponse head(String path) throws IOException, JSONException, NetworkProtocolException {
    final String fullUrl = getFullUrlAsString(path);
    if (DEBUG) {//ww w  . jav a 2  s. c  om
        Log.d(TAG, "HEAD " + fullUrl);
    }
    final HttpHead req = new HttpHead(fullUrl);

    return this.execute(req);
}

From source file:com.github.restdriver.serverdriver.RestServerDriver.java

/**
 * Perform an HTTP HEAD on a resource./*from www .  ja v  a 2 s. co  m*/
 * 
 * @param url The URL of a resource. Accepts any Object and calls .toString() on it.
 * @param modifiers Optional HTTP headers to put on the request.
 * @return A Response encapsulating the server's reply.
 */
public static Response head(Object url, AnyRequestModifier... modifiers) {
    ServerDriverHttpUriRequest request = new ServerDriverHttpUriRequest(new HttpHead(url.toString()));
    applyModifiersToRequest(modifiers, request);
    return doHttpRequest(request);
}

From source file:cn.edu.zzu.wemall.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.
 *//*from   www . j ava2 s. co  m*/
public RequestHandle head(Context context, String url, RequestParams params,
        AsyncHttpResponseHandler responseHandler) {
    return sendRequest(httpClient, httpContext,
            new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params)), null, responseHandler,
            context);
}

From source file:org.commonjava.couch.db.CouchManager.java

public boolean documentRevisionExists(final CouchDocument doc) throws CouchDBException {
    if (doc instanceof DenormalizedCouchDoc) {
        ((DenormalizedCouchDoc) doc).calculateDenormalizedFields();
    }/* w ww.j  av a 2s  . co  m*/

    final String docUrl = buildDocUrl(doc, doc.getCouchDocRev() != null);
    boolean exists = false;

    final HttpHead request = new HttpHead(docUrl);
    try {
        final HttpResponse response = client.executeHttpWithResponse(request, "Failed to ping database URL");

        final StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == SC_OK) {
            exists = true;
        } else if (statusLine.getStatusCode() != SC_NOT_FOUND) {
            final HttpEntity entity = response.getEntity();
            CouchError error;

            try {
                error = serializer.toError(entity);
            } catch (final IOException e) {
                throw new CouchDBException(
                        "Failed to ping database URL: %s.\nReason: %s\nError: Cannot read error status: %s", e,
                        docUrl, statusLine, e.getMessage());
            }

            throw new CouchDBException("Failed to ping database URL: %s.\nReason: %s\nError: %s", docUrl,
                    statusLine, error);
        }

        if (exists) {
            final Header etag = response.getFirstHeader("Etag");
            String rev = etag.getValue();
            if (rev.startsWith("\"") || rev.startsWith("'")) {
                rev = rev.substring(1);
            }

            if (rev.endsWith("\"") || rev.endsWith("'")) {
                rev = rev.substring(0, rev.length() - 1);
            }

            doc.setCouchDocRev(rev);
        }
    } finally {
        client.cleanup(request);
    }

    return exists;
}

From source file:com.soundcloud.playerapi.ApiWrapper.java

@Override
public Stream resolveStreamUrl(final String url) throws IOException {
    HttpResponse resp = safeExecute(null, addHeaders(Request.to(url).buildRequest(HttpHead.class)));
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return new Stream(url, url, resp);
    }//from w w w  . j  ava 2  s.  co  m

    String actualStreamUrl = null;
    int follows = 0;
    while (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
            && ++follows < MAX_REDIRECTS) {
        Header location = resp.getFirstHeader("Location");
        if (location != null && location.getValue() != null) {
            actualStreamUrl = location.getValue();
            resp = safeExecute(null, new HttpHead(actualStreamUrl));
        } else {
            throw new ResolverException("No location header", resp);
        }
    }

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return new Stream(url, actualStreamUrl, resp);
    } else {
        throw new ResolverException(
                follows == MAX_REDIRECTS ? "Terminated redirect loop" : "Invalid status code", resp);
    }
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java

/**
 * @inheritDoc/*from   w  ww .java  2  s.  c  om*/
 */
public long getFileSize(ArcMoverFile file) throws StorageAdapterException {
    HttpHost httpHost = new HttpHost(getHost(), ((HCAPProfile) getProfile()).getPort(),
            getProfile().getProtocol());

    String path = file.getPath();

    if (file.getParent().isVersionList() || file.isVersion()) {
        path = path + file.getVersionString();
    }

    HttpUriRequest request;
    try {
        request = new HttpHead(getProfile().resolvePath(path));
    } catch (IllegalArgumentException iae) {
        // If the path is not a valid URI, then fail only this object, not the job
        Throwable rootCause = iae;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        if (rootCause instanceof URISyntaxException) {
            throw new StorageAdapterLiteralException(rootCause);
        } else {
            throw iae;
        }
    }

    // Eventually we will just return this cookie which will be passed back to the caller.
    HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost);
    synchronized (savingCookieLock) {
        if (savedCookie != null) {
            throw new RuntimeException(
                    "This adapter already has a current connection to host -- cannot create two at once.");
        }
        savedCookie = cookie;
    }
    try {
        executeMethod(cookie);
        this.handleHttpResponse(cookie.getResponse(), "checking file size of", path);
    } catch (IOException e) {
        this.handleIOExceptionFromRequest(e, "checking file size of", path);
    } finally {
        close();
    }

    return Long.parseLong(cookie.getResponse().getFirstHeader("Content-Length").getValue());
}

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

/** Specify the next method by name.
 *
 * @param name of the method//  w  w  w  . jav a  2  s .co m
 * @param uri target
 * @return method object
 * @throws HttpException
 */
protected HttpRequestBase findMethod(final String name, final URI uri) throws HttpException {
    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);
    }

    throw new HttpException("Illegal method: " + name);
}

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

License:asdf

@Test
public void itUsesNoMultiLocationFormatResponseWithout302WithHead() throws Exception {
    final List<String> paths = new ArrayList<String>();
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=false");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=FALSE");
    paths.add("/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78&" + RouterFilter.REDIRECT_QUERY_PARAM
            + "=FalsE");

    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 {//from   www  .  ja  va  2s.  c o  m
            response = httpClient.execute(httpHead);
            assertThat("Failed getting 200 for request " + httpHead.getFirstHeader("Host").getValue(),
                    response.getStatusLine().getStatusCode(), equalTo(200));
            assertThat("Failed getting null body for HEAD request", response.getEntity(), nullValue());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}