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:anhttpclient.impl.DefaultWebBrowser.java

/**
 * {@inheritDoc}/*from   ww w .  j a v  a 2 s  .  co  m*/
 */
public WebResponse getResponse(WebRequest webRequest, String charset) throws IOException {
    initHttpClient();

    switch (webRequest.getRequestMethod()) {
    case GET:
        httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpGet(webRequest.getUrl())));
        break;
    case HEAD:
        httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpHead(webRequest.getUrl())));
        break;
    case OPTIONS:
        httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpOptions(webRequest.getUrl())));
        break;
    case TRACE:
        httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpTrace(webRequest.getUrl())));
        break;
    case DELETE:
        httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpDelete(webRequest.getUrl())));
        break;
    case POST:
        httpRequest.set(
                populateHttpEntityEnclosingRequestBaseMethod(webRequest, new HttpPost(webRequest.getUrl())));
        break;
    case PUT:
        httpRequest.set(
                populateHttpEntityEnclosingRequestBaseMethod(webRequest, new HttpPut(webRequest.getUrl())));
        break;
    default:
        throw new RuntimeException("Method not yet supported: " + webRequest.getRequestMethod());
    }

    WebResponse resp;

    HttpResponse response = executeMethod(httpRequest.get());
    if (response == null) {
        throw new IOException(
                "ANHTTPCLIENT. An empty response received from server. Possible reason: host is offline");
    }

    resp = processResponse(response, httpRequest.get(), charset);
    httpRequest.set(null);
    return resp;
}

From source file:org.codelibs.fess.crawler.client.http.HcHttpClient.java

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

From source file:org.trancecode.xproc.step.RequestParser.java

private HttpRequestBase constructMethod(final String method, final URI hrefUri) {
    final HttpEntity httpEntity = request.getEntity();
    final HeaderGroup headers = request.getHeaders();
    if (StringUtils.equalsIgnoreCase(HttpPost.METHOD_NAME, method)) {
        final HttpPost httpPost = new HttpPost(hrefUri);
        for (final Header h : headers.getAllHeaders()) {
            if (!StringUtils.equalsIgnoreCase("Content-Type", h.getName())) {
                httpPost.addHeader(h);//  w  w  w . ja  v a  2s  . com
            }
        }
        httpPost.setEntity(httpEntity);
        return httpPost;
    } else if (StringUtils.equalsIgnoreCase(HttpPut.METHOD_NAME, method)) {
        final HttpPut httpPut = new HttpPut(hrefUri);
        httpPut.setEntity(httpEntity);
        return httpPut;
    } else if (StringUtils.equalsIgnoreCase(HttpDelete.METHOD_NAME, method)) {
        final HttpDelete httpDelete = new HttpDelete(hrefUri);
        httpDelete.setHeaders(headers.getAllHeaders());
        return httpDelete;
    } else if (StringUtils.equalsIgnoreCase(HttpGet.METHOD_NAME, method)) {
        final HttpGet httpGet = new HttpGet(hrefUri);
        httpGet.setHeaders(headers.getAllHeaders());
        return httpGet;

    } else if (StringUtils.equalsIgnoreCase(HttpHead.METHOD_NAME, method)) {
        final HttpHead httpHead = new HttpHead(hrefUri);
        httpHead.setHeaders(headers.getAllHeaders());
        return httpHead;
    }
    return null;
}

From source file:com.imaginary.home.controller.CloudService.java

public boolean hasCommands() throws CommunicationException, ControllerException {
    HttpClient client = getClient(endpoint, proxyHost, proxyPort);
    HttpHead method = new HttpHead(endpoint + "/command");
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
    method.addHeader("x-imaginary-api-key", serviceId);

    if (token == null) {
        authenticate();/*from   w  w  w . j  a  va  2 s . c  om*/
    }
    String stringToSign = "head:/command:" + serviceId + ":" + token + ":" + timestamp + ":" + VERSION;

    try {
        method.addHeader("x-imaginary-signature", sign(apiKeySecret.getBytes("utf-8"), stringToSign));
    } catch (Exception e) {
        throw new ControllerException(e);
    }

    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() != HttpServletResponse.SC_NO_CONTENT) {
        parseError(response); // this will throw an exception
    }
    Header h = response.getFirstHeader("x-imaginary-has-commands");
    String val = (h == null ? "false" : h.getValue());

    return (val != null && val.equalsIgnoreCase("true"));
}

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

public boolean exists(final String path, final String query) throws StorageAdapterException {
    boolean result = false;

    HttpUriRequest request;/*from   w w  w . j  a  v a2  s  .co m*/
    HttpHost httpHost = new HttpHost(getHost(), ((HCAPProfile) getProfile()).getPort(),
            getProfile().getProtocol());

    String resolvedPath = path;

    if (!path.startsWith(HttpGatewayConstants.METADATA_MOUNT_URL_DIR)) {
        resolvedPath = getProfile().resolvePath(resolvedPath);
    }
    if (query != null && !query.equals("")) {
        resolvedPath = String.format("%s?%s", resolvedPath, query);
    }
    request = new HttpHead(resolvedPath);

    int statusCode = -1;
    try {
        // 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;
        }
        executeMethod(cookie);
        if (cookie.getResponse() != null)
            statusCode = cookie.getResponse().getStatusLine().getStatusCode();

        // Exists needs to return false for the cases where there is no server error, but the
        // object doesn't
        // exist. Otherwise it can go through standard response error handling
        result = true;
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_NO_CONTENT) {
            result = false;
        } else {
            this.handleHttpResponse(cookie.getResponse(), "checking existence of", path);
        }
    } catch (IOException e) {
        this.handleIOExceptionFromRequest(e, "checking existence of", path);
    } finally {
        close();
    }

    return result;
}

From source file:org.commonjava.aprox.client.core.AproxClientHttp.java

public HttpHead newJsonHead(final String url) {
    final HttpHead req = new HttpHead(url);
    addJsonHeaders(req);
    return req;
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Creates and returns a new HttpClient HTTP method based on the specified parameters.
 * @param submitMethod the submit method being used
 * @param uri the uri being used//from   w w w.  ja v  a  2 s.co m
 * @return a new HttpClient HTTP method based on the specified parameters
 */
private static HttpRequestBase buildHttpMethod(final HttpMethod submitMethod, final URI uri) {
    final HttpRequestBase method;
    switch (submitMethod) {
    case GET:
        method = new HttpGet(uri);
        break;

    case POST:
        method = new HttpPost(uri);
        break;

    case PUT:
        method = new HttpPut(uri);
        break;

    case DELETE:
        method = new HttpDelete(uri);
        break;

    case OPTIONS:
        method = new HttpOptions(uri);
        break;

    case HEAD:
        method = new HttpHead(uri);
        break;

    case TRACE:
        method = new HttpTrace(uri);
        break;

    case PATCH:
        method = new HttpPatch(uri);
        break;

    default:
        throw new IllegalStateException("Submit method not yet supported: " + submitMethod);
    }
    return method;
}

From source file:org.elasticsearch.client.RestClientSingleHostTests.java

private HttpUriRequest performRandomRequest(String method) throws Exception {
    String uriAsString = "/" + randomStatusCode(getRandom());
    URIBuilder uriBuilder = new URIBuilder(uriAsString);
    final Map<String, String> params = new HashMap<>();
    boolean hasParams = randomBoolean();
    if (hasParams) {
        int numParams = randomIntBetween(1, 3);
        for (int i = 0; i < numParams; i++) {
            String paramKey = "param-" + i;
            String paramValue = randomAsciiOfLengthBetween(3, 10);
            params.put(paramKey, paramValue);
            uriBuilder.addParameter(paramKey, paramValue);
        }//from   w w w .  j  a  v  a2s.c o  m
    }
    if (randomBoolean()) {
        //randomly add some ignore parameter, which doesn't get sent as part of the request
        String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        if (randomBoolean()) {
            ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        }
        params.put("ignore", ignore);
    }
    URI uri = uriBuilder.build();

    HttpUriRequest request;
    switch (method) {
    case "DELETE":
        request = new HttpDeleteWithEntity(uri);
        break;
    case "GET":
        request = new HttpGetWithEntity(uri);
        break;
    case "HEAD":
        request = new HttpHead(uri);
        break;
    case "OPTIONS":
        request = new HttpOptions(uri);
        break;
    case "PATCH":
        request = new HttpPatch(uri);
        break;
    case "POST":
        request = new HttpPost(uri);
        break;
    case "PUT":
        request = new HttpPut(uri);
        break;
    case "TRACE":
        request = new HttpTrace(uri);
        break;
    default:
        throw new UnsupportedOperationException("method not supported: " + method);
    }

    HttpEntity entity = null;
    boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean();
    if (hasBody) {
        entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }

    Header[] headers = new Header[0];
    final Set<String> uniqueNames = new HashSet<>();
    if (randomBoolean()) {
        headers = RestClientTestUtil.randomHeaders(getRandom(), "Header");
        for (Header header : headers) {
            request.addHeader(header);
            uniqueNames.add(header.getName());
        }
    }
    for (Header defaultHeader : defaultHeaders) {
        // request level headers override default headers
        if (uniqueNames.contains(defaultHeader.getName()) == false) {
            request.addHeader(defaultHeader);
        }
    }

    try {
        if (hasParams == false && hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, headers);
        } else if (hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, params, headers);
        } else {
            restClient.performRequest(method, uriAsString, params, entity, headers);
        }
    } catch (ResponseException e) {
        //all good
    }
    return request;
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * test is the returned status code matches the one of the HandlerException
 * thrown, with a HandlerException thrown before a body is set
 * /*from   ww w  . j  a  v a2  s.  c  om*/
 * @throws Exception
 *             on failure
 */
@Test
public void testExceptionStatusCodeBeforeBody() throws Exception {
    final int statusCode = 302;
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testStatusCode");
            response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server");
            throw new HandlerException(ResponseStatus.getInstanceByCode(statusCode));
        }
    }, serverBinding);

    try {
        URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpHead method = new HttpHead(serverURL);
        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(null);
        client.setRedirectHandler(nullRedirectHandler);
        HttpResponse response = client.execute(method);
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(statusCode, response.getStatusLine().getStatusCode());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}