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.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static HeadersBodyStatus doRequest(String type, String url, HeadersBody request) throws IOException {
    HttpRequestBase req;//from   w ww .java  2s  .co  m
    switch (type) {
    case "get":
        req = new HttpGet(url);
        break;
    case "post":
        req = new HttpPost(url);
        break;
    case "put":
        req = new HttpPut(url);
        break;
    case "delete":
        req = new HttpDelete(url);
        break;
    case "options":
        req = new HttpOptions(url);
        break;
    case "head":
        req = new HttpHead(url);
        break;
    default:
        throw new RuntimeException("Method not supported: " + type);
    }
    addHeaders(req, request.getHeaders());

    if (request.getBody() != null) {
        if (req instanceof HttpEntityEnclosingRequestBase == false) {
            throw new RuntimeException("Request type does not support body: " + type);
        }
        ((HttpEntityEnclosingRequestBase) req).setEntity(new InputStreamEntity(request.getBody()));
    }

    HttpResponse res = getHttpClient().execute(req);
    InputStream responseStream = null;
    if (res.getEntity() != null) {
        responseStream = res.getEntity().getContent();
    } else {
        responseStream = new InputStream() {
            @Override
            public int read() throws IOException {
                return -1;
            }
        };
    }

    Headers headers = new Headers();
    HeaderIterator it = res.headerIterator();
    while (it.hasNext()) {
        org.apache.http.Header header = it.nextHeader();
        headers.add(header.getName(), header.getValue());
    }

    return new HeadersBodyStatus(res.getStatusLine().toString(), headers, responseStream);
}

From source file:org.apache.camel.component.cm.CMProducer.java

@Override
protected void doStart() throws Exception {

    // log at debug level for singletons, for prototype scoped log at trace
    // level to not spam logs

    log.debug("Starting CMProducer");

    final CMConfiguration configuration = getConfiguration();

    if (configuration.isTestConnectionOnStartup()) {
        try {//w w  w.j  a v a2s.com
            log.debug("Checking connection - {}", getEndpoint().getCMUrl());
            HttpClientBuilder.create().build().execute(new HttpHead(getEndpoint().getCMUrl()));
            log.info("Connection to {}: OK", getEndpoint().getCMUrl());
        } catch (final Exception e) {
            log.info("Connection to {}: NOT AVAILABLE", getEndpoint().getCMUrl());
            throw new HostUnavailableException(e);
        }
    }

    // keep starting
    super.doStart();

    log.info("CMProducer started");
}

From source file:de.ecclesia.kipeto.repository.HttpRepositoryStrategy.java

@Override
public boolean contains(String id) throws IOException {
    HttpHead httpHead = new HttpHead(buildUrlForObject(id));
    HttpResponse response = client.execute(httpHead);

    int statusCode = response.getStatusLine().getStatusCode();

    return statusCode == HttpStatus.SC_OK;
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from  w w  w.  ja  v  a 2 s.c  om*/
@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());
        setEntityIfNonEmptyMultipart(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        setEntityIfNonEmptyMultipart(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());
        setEntityIfNonEmptyMultipart(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.nxt.zyl.data.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from   ww w.  j  av  a2 s  .com
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Request.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.getBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Request.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:co.uk.alt236.restclient4android.net.Connection.java

private HttpRequestBase setupHttpRequest(NetworkRequest request, URI uri) {
    String method = request.getAction().toUpperCase();
    String body = request.getRequestBody();

    HttpRequestBase httpReq = null;// w  w  w . jav  a  2 s . c o m
    HttpEntity entity = null;

    if (body != null) {
        body = body.trim();
        if (body.length() > 0) {
            entity = new ByteArrayEntity(body.getBytes());
        }
    }

    if ("GET".equals(method)) {
        httpReq = new HttpGet(uri);

    } else if ("POST".equals(method)) {
        httpReq = new HttpPost(uri);

        if (entity != null) {
            ((HttpPost) httpReq).setEntity(entity);
        }

    } else if ("PUT".equals(method)) {
        httpReq = new HttpPut(uri);
        if (entity != null) {
            ((HttpPut) httpReq).setEntity(entity);
        }

    } else if ("DELETE".equals(method)) {
        httpReq = new HttpDelete(uri);
    } else if ("HEAD".equals(method)) {
        httpReq = new HttpHead(uri);
    } else if ("TRACE".equals(method)) {
        httpReq = new HttpTrace(uri);
    } else if ("OPTIONS".equals(method)) {
        httpReq = new HttpOptions(uri);
    }

    setAuthentication(httpReq, request);
    setHeaders(httpReq, request);

    return httpReq;
}

From source file:code.google.restclient.core.Hitter.java

/**
 * Method to make POST or PUT request by sending http entity (as body)
 *///from w w w.  j ava2  s. c  om
public void hit(String url, String methodName, HttpHandler handler, Map<String, String> requestHeaders)
        throws Exception {

    if (DEBUG_ENABLED)
        LOG.debug("hit() - method => " + methodName + ", url => " + url);

    if (HttpGet.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> GET " + url);
        hit(url, new HttpGet(url), handler, requestHeaders);
    } else if (HttpHead.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> HEAD " + url);
        hit(url, new HttpHead(url), handler, requestHeaders);
    } else if (HttpDelete.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> DELETE " + url);
        hit(url, new HttpDelete(url), handler, requestHeaders);
    } else if (HttpOptions.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> OPTIONS " + url);
        hit(url, new HttpOptions(url), handler, requestHeaders);
    } else if (HttpTrace.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> TRACE " + url);
        hit(url, new HttpTrace(url), handler, requestHeaders);
    } else if (HttpPost.METHOD_NAME.equals(methodName)) { // POST
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> POST " + url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(handler.getReqBodyEntity());
        hit(url, httpPost, handler, requestHeaders);
    } else if (HttpPut.METHOD_NAME.equals(methodName)) { // PUT
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> PUT " + url);
        HttpPut httpPut = new HttpPut(url);
        httpPut.setEntity(handler.getReqBodyEntity());
        hit(url, httpPut, handler, requestHeaders);
    } else {
        throw new IllegalArgumentException("hit(): Unsupported method => " + methodName);
    }
}

From source file:net.netheos.pcsapi.providers.hubic.Swift.java

/**
 * Perform a quick HEAD request on the given object, to check existence and type.
 *///from  w w  w .  ja v  a 2s .c om
private Headers headOrNull(CPath path) {
    try {
        String url = getObjectUrl(path);
        HttpHead request = new HttpHead(url);

        RequestInvoker<CResponse> ri = getBasicRequestInvoker(request, path);
        CResponse response = retryStrategy.invokeRetry(ri);
        return response.getHeaders();

    } catch (CFileNotFoundException ex) {
        return null;
    }
}

From source file:com.sinacloud.scs.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request/* ww w .  j av a  2  s .  c o  m*/
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 *
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();

    /*
     * HttpClient cannot handle url in pattern of "http://host//path", so we
     * have to escape the double-slash between endpoint and resource-path
     * into "/%2F"
     */
    String uri = HttpUtils.appendUri(endpoint.toString(), request.getResourcePath(), true);
    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * Enable 100-continue support for PUT operations, since this is
         * where we're potentially uploading large amounts of data and want
         * to find out as early as possible if an operation will fail. We
         * don't want to do this for all operations since it will cause
         * extra latency in the network interaction.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new SCSClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}