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.olat.core.commons.services.webdav.WebDAVConnection.java

public HttpResponse head(URI uri) throws IOException, URISyntaxException {
    HttpHead propfind = new HttpHead(uri);
    HttpResponse response = execute(propfind);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    return response;
}

From source file:com.lovebridge.library.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///w w  w.j  ava 2s.  c  o m
@SuppressWarnings("deprecation")
/* protected */ 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:org.fcrepo.integration.http.api.ldp.LdprIT.java

@Test
public void testMustUseEntityTags() throws IOException {
    client.execute(postObjMethod("Ldpr428"));
    final HttpHead testMethod = new HttpHead(serverAddress + "Ldpr428");
    final HttpResponse response = client.execute(testMethod);
    assertTrue(response.containsHeader("ETag"));
}

From source file:com.wrapp.android.webimage.ImageDownloader.java

public static Date getServerTimestamp(final URL imageUrl) {
    Date expirationDate = new Date();

    try {//from  ww w.  ja  v a2 s .  co m
        final String imageUrlString = imageUrl.toString();
        if (imageUrlString == null || imageUrlString.length() == 0) {
            throw new Exception("Passed empty URL");
        }
        LogWrapper.logMessage("Requesting image '" + imageUrlString + "'");
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpParams httpParams = httpClient.getParams();
        httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
        final HttpHead httpHead = new HttpHead(imageUrlString);
        final HttpResponse response = httpClient.execute(httpHead);

        Header[] header = response.getHeaders("Expires");
        if (header != null && header.length > 0) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
            expirationDate = dateFormat.parse(header[0].getValue());
            LogWrapper
                    .logMessage("Image at " + imageUrl.toString() + " expires on " + expirationDate.toString());
        }
    } catch (Exception e) {
        LogWrapper.logException(e);
    }

    return expirationDate;
}

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

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

From source file:org.commonjava.indy.httprox.AutoCreateRepoWithTrackingIdTest.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);/* w w w  .j av  a 2s . c  om*/

    final HttpGet get = new HttpGet(url);
    CloseableHttpClient client = proxiedHttp(USER, PASS);
    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);
    }

    // Remote
    String remote = creator.formatId(HOST, 0, 0, TRACKING_ID, StoreType.remote);
    final RemoteRepository remoteRepo = this.client.stores()
            .load(new StoreKey(GENERIC_PKG_KEY, StoreType.remote, remote), RemoteRepository.class);

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

    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);
    }

    // Hosted
    String hosted = creator.formatId(HOST, 0, 0, TRACKING_ID, StoreType.hosted);
    final HostedRepository hostedRepo = this.client.stores()
            .load(new StoreKey(GENERIC_PKG_KEY, StoreType.hosted, hosted), HostedRepository.class);

    assertThat(hostedRepo, notNullValue());

    // Group
    final Group group = this.client.stores().load(new StoreKey(GENERIC_PKG_KEY, StoreType.group,
            creator.formatId(HOST, 0, 0, TRACKING_ID, StoreType.group)), Group.class);

    assertThat(group, notNullValue());

    List<StoreKey> constituents = group.getConstituents();

    assertThat(constituents.contains(remoteRepo.getKey()), equalTo(true));
    assertThat(constituents.contains(hostedRepo.getKey()), equalTo(true));

}

From source file:org.camunda.connect.httpclient.impl.AbstractHttpConnector.java

@SuppressWarnings("unchecked")
protected <T extends HttpRequestBase> T createHttpRequestBase(Q request) {
    String url = request.getUrl();
    if (url != null && !url.trim().isEmpty()) {
        String method = request.getMethod();
        if (HttpGet.METHOD_NAME.equals(method)) {
            return (T) new HttpGet(url);
        } else if (HttpPost.METHOD_NAME.equals(method)) {
            return (T) new HttpPost(url);
        } else if (HttpPut.METHOD_NAME.equals(method)) {
            return (T) new HttpPut(url);
        } else if (HttpDelete.METHOD_NAME.equals(method)) {
            return (T) new HttpDelete(url);
        } else if (HttpPatch.METHOD_NAME.equals(method)) {
            return (T) new HttpPatch(url);
        } else if (HttpHead.METHOD_NAME.equals(method)) {
            return (T) new HttpHead(url);
        } else if (HttpOptions.METHOD_NAME.equals(method)) {
            return (T) new HttpOptions(url);
        } else if (HttpTrace.METHOD_NAME.equals(method)) {
            return (T) new HttpTrace(url);
        } else {//from   w  w  w .  j a va  2s. c o m
            throw LOG.unknownHttpMethod(method);
        }
    } else {
        throw LOG.requestUrlRequired();
    }
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

protected static HttpHead headObjMethod(final String id) {
    return new HttpHead(serverAddress + id);
}

From source file:com.intel.cosbench.client.http.HttpClientUtil.java

public static HttpHead makeHttpHead(String url) {
    return new HttpHead(url);
}

From source file:com.sayar.requests.impl.HttpClientRequestHandler.java

public Response execute(final RequestArguments args) throws AuthenticationException, InvalidParameterException {
    // Parse params
    final String url = args.getUrl();
    final Map<String, String> params = args.getParams();
    final HttpAuthentication httpAuth = args.getHttpAuth();

    String formattedUrl;// ww  w. j  a v a2  s  .co m
    try {
        formattedUrl = RequestHandlerUtils.formatUrl(url, params);
    } catch (final UnsupportedEncodingException e) {
        Log.e(RequestsConstants.LOG_TAG, "Unsupported Encoding Exception in Url Parameters.", e);
        throw new InvalidParameterException("Url Parameter Encoding is invalid.");

    }

    final RequestMethod method = args.getMethod();
    HttpUriRequest request = null;
    if (method == RequestMethod.GET) {
        request = new HttpGet(formattedUrl);
    } else if (method == RequestMethod.DELETE) {
        request = new HttpDelete(formattedUrl);
    } else if (method == RequestMethod.OPTIONS) {
        request = new HttpOptions(formattedUrl);
    } else if (method == RequestMethod.HEAD) {
        request = new HttpHead(formattedUrl);
    } else if (method == RequestMethod.TRACE) {
        request = new HttpTrace(formattedUrl);
    } else if (method == RequestMethod.POST || method == RequestMethod.PUT) {
        request = method == RequestMethod.POST ? new HttpPost(formattedUrl) : new HttpPut(formattedUrl);
        if (args.getRequestEntity() != null) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(args.getRequestEntity());
        }
    } else {
        throw new InvalidParameterException("Request Method is not set.");
    }

    if (httpAuth != null) {
        try {
            HttpClientRequestHandler.addAuthentication(request, httpAuth);
        } catch (final AuthenticationException e) {
            Log.e(RequestsConstants.LOG_TAG, "Adding Authentication Failed.", e);
            throw e;
        }
    }
    if (args.getHeaders() != null) {
        HttpClientRequestHandler.addHeaderParams(request, args.getHeaders());
    }

    final Response response = new Response();

    final HttpClient client = this.getHttpClient(args);

    try {
        final HttpResponse httpResponse = client.execute(request);

        response.setResponseVersion(httpResponse.getProtocolVersion());
        response.setStatusAndCode(httpResponse.getStatusLine());

        final HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            // Convert the stream into a string and store into the RAW
            // field.
            // InputStream instream = entity.getContent();
            // response.setRaw(RequestHandlerUtils.convertStreamToString(instream));
            // instream.close(); // Closing the input stream will trigger
            // connection release

            // TODO: Perhaps we should be dealing with the charset
            response.setRaw(EntityUtils.toString(entity));

            try {
                // Get the Content Type
                final String contenttype = entity.getContentType().getValue();

                RequestParser parser = null;

                // Check if a request-specific parser was set.
                if (args.getRequestParser() == null) {
                    // Parse the request according to the user's wishes.
                    final String extractionFormat = args.getParseAs();

                    // Determine extraction format if none are set.
                    if (extractionFormat == null) {
                        // If we can not find an appropriate parser, the
                        // default one will be returned.
                        parser = RequestParserFactory.findRequestParser(contenttype);
                    } else {
                        // Try to get the requested parser. This will throw
                        // an exception if we can't get it.
                        parser = RequestParserFactory.getRequestParser(extractionFormat);
                    }
                } else {
                    // Set a request specific parser.
                    parser = args.getRequestParser();
                }

                // Parse the content.. and if it throws an exception log it.
                final Object result = parser.parse(response.getRaw());
                // Check the result of the parser.
                if (result != null) {
                    response.setContent(result);
                    response.setParsedAs(parser.getName());
                } else {
                    // If the parser returned nothing (and most likely it
                    // wasn't the default parser).

                    // We already have the raw response, user the default
                    // parser fallback.
                    response.setContent(RequestParserFactory.DEFAULT_PARSER.parse(response.getRaw()));
                    response.setParsedAs(RequestParserFactory.DEFAULT_PARSER.getName());
                }
            } catch (final InvalidParameterException e) {
                Log.e(RequestsConstants.LOG_TAG, "Parser Requested Could Not Be Found.", e);
                throw e;
            } catch (final Exception e) {
                // Catch any parsing exception.
                Log.e(RequestsConstants.LOG_TAG, "Parser Failed Exception.", e);
                // Informed it was parsed as nothing... aka look at the raw
                // string.
                response.setParsedAs(null);
            }

        } else {
            if (args.getMethod() != RequestMethod.HEAD) {
                Log.w(RequestsConstants.LOG_TAG, "Entity is empty?");
            }
        }
    } catch (final ClientProtocolException e) {
        Log.e(RequestsConstants.LOG_TAG, "Client Protocol Exception", e);
    } catch (final IOException e) {
        Log.e(RequestsConstants.LOG_TAG, "IO Exception.", e);
    } finally {
    }

    return response;
}