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:cz.incad.Kramerius.audio.AudioHttpRequestForwarder.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);
}

From source file:io.undertow.server.handlers.file.FileHandlerTestCase.java

@Test
public void testHeadRequest() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path file = Paths.get(getClass().getResource("page.html").toURI());
    Path rootPath = file.getParent();
    try {//from w ww.j  ava  2s.  c  om
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(rootPath, 10485760))
                        .setDirectoryListingEnabled(true))));

        HttpHead get = new HttpHead(DefaultServer.getDefaultServerURL() + "/path/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals(Long.toString(Files.size(file)),
                result.getHeaders(Headers.CONTENT_LENGTH_STRING)[0].getValue());
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.norconex.collector.http.fetch.impl.SimpleHttpHeadersFetcher.java

@Override
public Properties fetchHTTPHeaders(DefaultHttpClient httpClient, String url) {
    Properties metadata = new Properties();
    HttpHead method = null;/*from  ww  w  .ja va2  s  . c  o m*/
    try {
        method = new HttpHead(url);
        // Execute the method.
        HttpResponse response = httpClient.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        if (!ArrayUtils.contains(validStatusCodes, statusCode)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Invalid HTTP status code (" + response.getStatusLine() + ") for URL: " + url);
            }
            return null;
        }

        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];
            String name = header.getName();
            if (StringUtils.isNotBlank(headersPrefix)) {
                name = headersPrefix + name;
            }

            metadata.addString(name, header.getValue());
        }
        return metadata;
    } catch (Exception e) {
        LOG.error("Cannot fetch document: " + url + " (" + e.getMessage() + ")", e);
        throw new HttpCollectorException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.mashape.unirest.android.http.HttpClientHelper.java

private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }// w  ww  . java2 s.  c o m
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        //reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        //reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:com.google.devtools.build.lib.remote.blobstore.RestBlobStore.java

@Override
public boolean containsKey(String key) throws IOException {
    HttpClient client = clientFactory.build();
    HttpHead head = new HttpHead(baseUrl + "/" + CAS_PREFIX + "/" + key);
    return client.execute(head, response -> {
        int statusCode = response.getStatusLine().getStatusCode();
        return HttpStatus.SC_OK == statusCode;
    });/*from   w  w w  .  j  a v a  2s . c  om*/
}

From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java

/**
 * Maps POM requests simulating a Maven 2 directory structure.
 * @throws IOException/*  w  w w.  j  a  va 2  s.  c  om*/
 */
@GET
@Path("{groupIdPath:[a-zA-Z0-9\\-\\_]+(/[a-zA-Z0-9\\-\\_]+)*}" + "/{artifactId:[a-zA-Z0-9\\-\\_\\.]+}"
        + "/{version:\\d+(\\.\\d+)*}" + "/{artifactIdFilename:[a-zA-Z0-9\\-\\_\\.]+}"
        + "-{versionFilename:\\d+(\\.\\d+)*}" + ".{fileExtension:pom(\\.sha1)?}")
@Timed
public Response getPom(@PathParam("groupIdPath") String groupIdPath, @PathParam("artifactId") String artifactId,
        @PathParam("version") String version, @PathParam("artifactIdFilename") String artifactIdFilename,
        @PathParam("versionFilename") String versionFilename, @PathParam("fileExtension") String fileExtension)
        throws IOException {

    String groupId = mapGroupId(groupIdPath);
    if (!validateBasicParams(groupId, artifactId, version, artifactIdFilename, versionFilename)) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    ArtifactType artifactType = getArtifactType(artifactId);

    // validate that version exists
    String url = getPomValidateUrl(artifactType, version);
    log.info("Validate file: {}", url);
    HttpHead get = new HttpHead(url);
    HttpResponse response = httpClient.execute(get);
    try {
        if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }

    String xml = PomBuilder.build(groupId, artifactId, version, "pom");

    if (StringUtils.equals(fileExtension, "pom")) {
        return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
    }
    if (StringUtils.equals(fileExtension, "pom.sha1")) {
        return Response.ok(DigestUtils.sha1Hex(xml)).type(MediaType.TEXT_PLAIN).build();
    }
    return Response.status(Response.Status.NOT_FOUND).build();
}

From source file:org.xmlsh.internal.commands.http.java

@Override
public int run(List<XValue> args) throws Exception {

    Options opts = new Options(
            "retry:,get:,put:,post:,head:,options:,delete:,connectTimeout:,contentType:,readTimeout:,+useCaches,+followRedirects,user:,password:,H=add-header:+,disableTrust:,keystore:,keypass:,sslproto:,output-headers=ohead:");
    opts.parse(args);//from  w w w .  j a  va2s  . c o m

    setSerializeOpts(getSerializeOpts(opts));

    HttpRequestBase method;

    String surl = null;

    if (opts.hasOpt("get")) {
        surl = opts.getOptString("get", null);
        method = new HttpGet(surl);
    } else if (opts.hasOpt("put")) {
        surl = opts.getOptString("put", null);
        method = new HttpPut(surl);
        ((HttpPut) method).setEntity(getInputEntity(opts));
    } else if (opts.hasOpt("post")) {
        surl = opts.getOptString("post", null);
        method = new HttpPost(surl);
        ((HttpPost) method).setEntity(getInputEntity(opts));

    } else if (opts.hasOpt("head")) {
        surl = opts.getOptString("head", null);
        method = new HttpHead(surl);
    } else if (opts.hasOpt("options")) {
        surl = opts.getOptString("options", null);
        method = new HttpOptions(surl);
    } else if (opts.hasOpt("delete")) {
        surl = opts.getOptString("delete", null);
        method = new HttpDelete(surl);
    } else if (opts.hasOpt("trace")) {
        surl = opts.getOptString("trace", null);
        method = new HttpTrace(surl);
    } else {
        surl = opts.getRemainingArgs().get(0).toString();
        method = new HttpGet(surl);
    }

    if (surl == null) {
        usage();
        return 1;
    }

    int ret = 0;

    HttpHost host = new HttpHost(surl);

    DefaultHttpClient client = new DefaultHttpClient();

    setOptions(client, host, opts);

    List<XValue> headers = opts.getOptValues("H");
    if (headers != null) {
        for (XValue v : headers) {
            StringPair pair = new StringPair(v.toString(), '=');
            method.addHeader(pair.getLeft(), pair.getRight());
        }

    }

    int retry = opts.getOptInt("retry", 0);
    long delay = 1000;

    HttpResponse resp = null;

    do {
        try {
            resp = client.execute(method);
            break;
        } catch (IOException e) {
            mShell.printErr("Exception running http" + ((retry > 0) ? " retrying ... " : ""), e);
            if (retry > 0) {
                Thread.sleep(delay);
                delay *= 2;
            } else
                throw e;
        }
    } while (retry-- > 0);

    HttpEntity respEntity = resp.getEntity();
    if (respEntity != null) {
        InputStream ins = respEntity.getContent();
        if (ins != null) {
            try {
                Util.copyStream(ins, getStdout().asOutputStream(getSerializeOpts()));
            } finally {
                ins.close();
            }
        }
    }

    ret = resp.getStatusLine().getStatusCode();
    if (opts.hasOpt("output-headers"))
        writeHeaders(opts.getOptStringRequired("output-headers"), resp.getStatusLine(), resp.getAllHeaders());

    return ret;
}

From source file:com.oplay.nohelper.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from   ww w . j  a v a2  s .c  o m
@SuppressWarnings("deprecation")
public static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.sangupta.jerry.http.WebRequest.java

/**
* Create a HTTP HEAD based {@link WebRequest} for the given {@link URI}
* 
* @param uri// w ww .ja va  2  s  .c  o  m
*            the {@link URI} for which to create web request
* 
* @return the {@link WebRequest} object thus created
 */
public static WebRequest head(final URI uri) {
    return new WebRequest(new HttpHead(uri));
}

From source file:piecework.content.concrete.RemoteResource.java

protected synchronized void ensureInitialized() {
    if (!this.initialized) {
        this.initialized = true;
        HttpCacheContext context = HttpCacheContext.create();
        HttpHead head = new HttpHead(uri);

        final ConnectionCloser connectionCloser = new ConnectionCloser();
        try {//from w ww .  j  a  va2s. co m
            LOG.info("Retrieving resource from " + uri.toString());
            CloseableHttpResponse response = client.execute(head, context);
            connectionCloser.setResponse(response);
            addDetails(response);
        } catch (Exception e) {
            LOG.error("Unable to retrieve details about remote resource", e);
        } finally {
            connectionCloser.closeEverythingQuietly();
        }
    }
}