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.apache.jena.fuseki.http.DatasetGraphAccessorHTTP.java

private boolean doHead(String url) {
    HttpUriRequest httpHead = new HttpHead(url);
    try {/*from   w ww  . ja v a 2 s .  c o  m*/
        exec(url, null, httpHead, false);
        return true;
    } catch (FusekiRequestException ex) {
        if (ex.getStatusCode() == HttpSC.NOT_FOUND_404)
            return false;
        throw ex;
    }
}

From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java

@Override
public HTTPResponse fetch(final HTTPRequest request) throws IOException {
    final HttpClient httpClient = new DefaultHttpClient();

    final URL url = request.getURL();
    final HTTPRequestMethod requestMethod = request.getRequestMethod();

    HttpUriRequest httpUriRequest = null;

    try {//  w  w w . j  a v a  2  s.  c o m
        final byte[] payload = request.getPayload();

        switch (requestMethod) {

        case GET:
            final HttpGet httpGet = new HttpGet(url.toURI());

            // FIXME: GET with payload
            httpUriRequest = httpGet;
            break;

        case DELETE:
            httpUriRequest = new HttpDelete(url.toURI());
            break;

        case HEAD:
            httpUriRequest = new HttpHead(url.toURI());
            break;

        case POST:
            final HttpPost httpPost = new HttpPost(url.toURI());

            if (null != payload) {
                httpPost.setEntity(new ByteArrayEntity(payload));
            }
            httpUriRequest = httpPost;
            break;

        case PUT:
            final HttpPut httpPut = new HttpPut(url.toURI());

            if (null != payload) {
                httpPut.setEntity(new ByteArrayEntity(payload));
            }
            httpUriRequest = httpPut;
            break;

        default:
            throw new RuntimeException("Unsupported HTTP request method[" + requestMethod.name() + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "URL fetch failed", e);

        throw new IOException("URL fetch failed [msg=" + e.getMessage() + ']');
    }

    final List<HTTPHeader> headers = request.getHeaders();

    for (final HTTPHeader header : headers) {
        httpUriRequest.addHeader(header.getName(), header.getValue());
    }

    final HttpResponse res = httpClient.execute(httpUriRequest);

    final HTTPResponse ret = new HTTPResponse();

    ret.setContent(EntityUtils.toByteArray(res.getEntity()));
    ret.setResponseCode(res.getStatusLine().getStatusCode());

    return ret;
}

From source file:org.commonjava.indy.httprox.AutoCreateRepoAndRetrievePomTest.java

@Test
public void run() throws Exception {
    final String testRepo = "test";
    final PomRef pom = loadPom("simple.pom", Collections.<String, String>emptyMap());
    final String url = server.formatUrl(testRepo, pom.path);
    server.expect(url, 200, pom.pom);/*from  w  w w .j  a  v a  2s.  co m*/

    final HttpGet get = new HttpGet(url);
    CloseableHttpClient client = proxiedHttp();
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(get, proxyContext(USER, PASS));
        stream = response.getEntity().getContent();
        final String resultingPom = IOUtils.toString(stream);

        assertThat(resultingPom, notNullValue());
        assertThat(resultingPom, equalTo(pom.pom));
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(get, response, client);
    }

    final RemoteRepository remoteRepo = this.client.stores().load(
            new StoreKey(GENERIC_PKG_KEY, StoreType.remote, "httprox_127-0-0-1_" + server.getPort()),
            RemoteRepository.class);

    assertThat(remoteRepo, notNullValue());
    assertThat(remoteRepo.getUrl(), equalTo(server.getBaseUri()));
    assertThat(remoteRepo.isPassthrough(), equalTo(true));

    String pomUrl = this.client.content().contentUrl(remoteRepo.getKey(), testRepo, pom.path)
            + "?cache-only=true";
    HttpHead head = new HttpHead(pomUrl);
    client = HttpClients.createDefault();

    try {
        response = client.execute(head);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    } finally {
        HttpResources.cleanupResources(head, response, client);
    }

}

From source file:eionet.gdem.utils.HttpUtils.java

/**
 * Method checks whether the resource behind the given URL exist. The method calls HEAD request and if the resonse code is 200,
 * then returns true. If exception is thrown or response code is something else, then the result is false.
 *
 * @param url URL//from ww  w . ja  v  a  2 s . com
 * @return True if resource behind the url exists.
 */
public static boolean urlExists(String url) {

    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpHead method = new HttpHead(url);
    CloseableHttpResponse response = null;
    try {
        // Execute the method.
        response = client.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_OK;
        /*} catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
            return false;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        method.releaseConnection();
        try {
            response.close();
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:com.vanillasource.gerec.httpclient.AsyncApacheHttpClient.java

@Override
public CompletableFuture<HttpResponse> doHead(URI uri, HttpRequest.HttpRequestChange change) {
    return execute(new HttpHead(uri), change);
}

From source file:org.wso2.carbon.esb.passthru.transport.test.ESBJAVA1897HttpHeadMethodTestCase.java

@Test(groups = "wso2.esb", description = "test to verify that the HTTP HEAD method works with PTT.")
public void testHttpHeadMethod() throws Exception {
    Thread.sleep(5000);/*from w w  w  . j av  a 2 s  . c om*/
    String restURL = (getProxyServiceURLHttp(SERVICE_NAME)) + "/students";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpHead httpHead = new HttpHead(restURL);
    HttpResponse response = httpclient.execute(httpHead);

    // http head method should return a 202 Accepted
    assertTrue(response.getStatusLine().getStatusCode() == 202);
    // it should not contain a message body
    assertTrue(response.getEntity() == null);

}

From source file:org.commonjava.indy.httprox.ProxyHttpsWildcardHostCertTest.java

protected String head(String url, boolean withCACert, String user, String pass) throws Exception {
    CloseableHttpClient client;//from  w  w  w . j  a va2  s .  c o  m

    if (withCACert) {
        File jks = new File(etcDir, "ssl/ca.jks");
        KeyStore trustStore = getTrustStore(jks);
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        client = proxiedHttp(user, pass, socketFactory);
    } else {
        client = proxiedHttp(user, pass);
    }

    HttpHead req = new HttpHead(url);
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(req, proxyContext(user, pass));
        /*stream = response.getEntity().getContent();
        final String resulting = IOUtils.toString( stream );
                
        assertThat( resulting, notNullValue() );
        System.out.println( "\n\n>>>>>>>\n\n" + resulting + "\n\n" );*/

        return response.toString();
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(req, response, client);
    }
}

From source file:cz.incad.kramerius.audio.servlets.ServletAudioHttpRequestForwarder.java

public Void forwardHeadRequest(URL url) throws IOException, URISyntaxException {
    LOGGER.log(Level.INFO, "forwarding {0}", url);
    HttpHead repositoryRequest = new HttpHead(url.toURI());
    forwardSelectedRequestHeaders(clientToProxyRequest, repositoryRequest);
    //printRepositoryRequestHeaders(repositoryRequest);
    HttpResponse repositoryResponse = httpClient.execute(repositoryRequest);
    //printRepositoryResponseHeaders(repositoryResponse);
    forwardSelectedResponseHeaders(repositoryResponse, proxyToClientResponse);
    forwardResponseCode(repositoryResponse, proxyToClientResponse);
    return null;//from  ww w .  jav a2  s. co  m
}

From source file:org.commonjava.indy.httprox.AutoCreateRepoAndRetrieveNoCacheFileTest.java

@Test
public void run() throws Exception {
    final String path = "org/foo/bar/1.0/bar-1.0.nocache";
    final String content = "This is a test: " + System.nanoTime();

    final String testRepo = "test";

    final String url = server.formatUrl(testRepo, path);

    server.expect(url, 200, content);/*from w  w w  .  ja v  a  2s .  c  o  m*/

    final HttpGet get = new HttpGet(url);
    CloseableHttpClient client = proxiedHttp();
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(get, proxyContext(USER, PASS));
        stream = response.getEntity().getContent();
        final String resultingPom = IOUtils.toString(stream);

        assertThat(resultingPom, notNullValue());
        assertThat(resultingPom, equalTo(content));
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(get, response, client);
    }

    final RemoteRepository remoteRepo = this.client.stores().load(
            new StoreKey(GENERIC_PKG_KEY, StoreType.remote, "httprox_127-0-0-1_" + server.getPort()),
            RemoteRepository.class);

    assertThat(remoteRepo, notNullValue());
    assertThat(remoteRepo.getUrl(), equalTo(server.getBaseUri()));

    String pomUrl = this.client.content().contentUrl(remoteRepo.getKey(), testRepo, path) + "?cache-only=true";
    System.out.println("pomUrl:: " + pomUrl);

    HttpHead head = new HttpHead(pomUrl);
    client = HttpClients.createDefault();

    try {
        response = client.execute(head);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
    } finally {
        HttpResources.cleanupResources(head, response, client);
    }

}

From source file:org.apache.geode.rest.internal.web.RestSecurityDUnitTest.java

protected HttpResponse doHEAD(String query, String username, String password) throws MalformedURLException {
    HttpHead httpHead = new HttpHead(CONTEXT + query);
    return doRequest(httpHead, username, password);
}