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:com.cloudant.mazha.HttpRequests.java

HttpResponse head(URI uri) {
    HttpHead head = new HttpHead(uri);
    return executeRequest(head);
}

From source file:com.google.wireless.speed.speedometer.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override//from ww w . j a v  a2s  .  c  o  m
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Log.i(SpeedometerApp.TAG, MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(SpeedometerApp.TAG, "Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:org.fcrepo.apix.registry.impl.HttpRegistry.java

@Override
public boolean contains(final URI uri) {
    try (CloseableHttpResponse response = client.execute(new HttpHead(uri))) {
        return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }/*from   w w w  .j a v a2s  .c  o m*/
}

From source file:com.github.lpezet.antiope.dao.DefaultHttpRequestFactory.java

@Override
public HttpRequestBase createHttpRequest(Request<?> pRequest, APIConfiguration pConfiguration,
        HttpContext pHttpContext, ExecutionContext pExecutionContext) {
    // Signing request is any signer.
    if (pExecutionContext.getSigner() != null && pExecutionContext.getCredentials() != null) {
        pExecutionContext.getMetrics().startEvent(APIRequestMetrics.RequestSigningTime);
        try {/*from   ww  w .ja  v  a2  s  .c  o  m*/
            pExecutionContext.getSigner().sign(pRequest, pExecutionContext.getCredentials());
        } finally {
            pExecutionContext.getMetrics().endEvent(APIRequestMetrics.RequestSigningTime);
        }
    }

    URI oEndpoint = pRequest.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 oUri = HttpUtils.appendUri(oEndpoint.toString(), pRequest.getResourcePath(), true);
    String oEncodedParams = HttpUtils.encodeParameters(pRequest);

    /*
     * 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 oRequestHasNoPayload = pRequest.getContent() == null;
    boolean oRequestIsPost = pRequest.getHttpMethod() == HttpMethodName.POST;
    boolean oPutParamsInUri = !oRequestIsPost || oRequestHasNoPayload;
    if (oEncodedParams != null && oPutParamsInUri) {
        oUri += QMARK + oEncodedParams;
    }

    HttpRequestBase oHttpRequest;
    if (pRequest.getHttpMethod() == HttpMethodName.POST) {
        HttpPost oPostMethod = new HttpPost(oUri);

        /*
         * 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 API 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 (pRequest.getContent() == null && oEncodedParams != null) {
            oPostMethod.setEntity(newStringEntity(oEncodedParams));
        } else if (pRequest.getContent() != null) {
            oPostMethod.setEntity(new RepeatableInputStreamRequestEntity(pRequest));
        }
        oHttpRequest = oPostMethod;
    } else if (pRequest.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(oUri);

        /*
         * 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 (pPreviousEntity != null) {
        //   putMethod.setEntity(pPreviousEntity);
        //} else 
        if (pRequest.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(pRequest);
            if (pRequest.getHeaders().get(CONTENT_LENGTH) == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }

        oHttpRequest = putMethod;
    } else if (pRequest.getHttpMethod() == HttpMethodName.GET) {
        oHttpRequest = new HttpGet(oUri);
    } else if (pRequest.getHttpMethod() == HttpMethodName.DELETE) {
        oHttpRequest = new HttpDelete(oUri);
    } else if (pRequest.getHttpMethod() == HttpMethodName.HEAD) {
        oHttpRequest = new HttpHead(oUri);
    } else {
        throw new APIClientException("Unknown HTTP method name: " + pRequest.getHttpMethod());
    }

    configureHeaders(oHttpRequest, pRequest, pExecutionContext, pConfiguration);

    return oHttpRequest;
}

From source file:com.android.volley.toolbox.http.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///w ww . java 2 s .  c  om
@SuppressWarnings("deprecation")
/* protected */ HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {

    String url = request.getUrl();
    if (mUrlRewriter != null) {
        url = mUrlRewriter.rewriteUrl(url);
        if (url == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
    }
    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.getBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(url);
            //                    postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(url);
        }
    }
    case Method.GET:
        return new HttpGet(url);
    case Method.DELETE:
        return new HttpDelete(url);
    case Method.POST: {
        HttpPost postRequest = new HttpPost(url);
        //                postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(url);
        //                putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(url);
    case Method.OPTIONS:
        return new HttpOptions(url);
    case Method.TRACE:
        return new HttpTrace(url);
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(url);
        //                patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.fcrepo.apix.binding.impl.RuntimeExtensionBinding.java

/** Just does a dumb dereference and lookup */
@Override//from  w ww  .j ava 2s .  com
public Collection<Extension> getExtensionsFor(final URI resourceURI, final Collection<Extension> from) {

    if (from.isEmpty()) {
        return Collections.emptyList();
    }

    // Use object contents for reasoning, or if binary the binary's description
    try (final CloseableHttpResponse response = httpClient.execute(new HttpHead(resourceURI))) {

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(String.format("Got unexpected status code %s in HEAD to <%s>",
                    response.getStatusLine().getStatusCode(), resourceURI));
        }

        final List<FcrepoLink> describedByLinks = Arrays.asList(response.getHeaders("Link")).stream()
                .map(Header::getValue).map(FcrepoLink::new).filter(l -> "describedby".equals(l.getRel()))
                .collect(Collectors.toList());

        if (!describedByLinks.isEmpty()) {
            if (describedByLinks.size() > 1) {
                throw new RuntimeException(
                        String.format("Ambiguous; more than one describes header for <%s>", resourceURI));
            }

            LOG.debug("Using <{}> for inference about binary <{}>", describedByLinks.get(0).getUri(),
                    resourceURI);

            try (WebResource resource = registry.get(describedByLinks.get(0).getUri())) {
                return getExtensionsFor(
                        WebResource.of(resource.representation(), resource.contentType(), resourceURI, null),
                        from);
            }

        } else {
            try (WebResource resource = registry.get(resourceURI)) {
                return getExtensionsFor(resource, from);
            }
        }

    } catch (final Exception e) {
        throw new RuntimeException("Could not get triples for reasoning over " + resourceURI, e);
    }
}

From source file:org.artifactory.repo.remote.browse.S3RepositoryBrowser.java

/**
 * @param url    The URL to check//from   ww  w .  java2 s  .  com
 * @param client Http client to use
 * @return True if the url points to an S3 repository.
 */
public static boolean isS3Repository(String url, CloseableHttpClient client) {
    HttpHead headMethod = new HttpHead(HttpUtils.encodeQuery(url));
    try (CloseableHttpResponse response = client.execute(headMethod)) {
        Header s3RequestId = response.getFirstHeader(HEADER_S3_REQUEST_ID);
        return s3RequestId != null;
    } catch (IOException e) {
        log.debug("Failed detecting S3 repository: " + e.getMessage(), e);
    }
    return false;
}

From source file:com.base.net.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from w  w  w  .  j  a v  a  2s .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());
        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.rapidoid.http.HttpClientUtil.java

private static HttpRequestBase createReq(HttpReq config, String url) {
    HttpRequestBase req;//  w  ww  . ja v a2  s.c  om
    switch (config.verb()) {
    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 PATCH:
        req = new HttpPatch(url);
        break;

    case OPTIONS:
        req = new HttpOptions(url);
        break;

    case HEAD:
        req = new HttpHead(url);
        break;

    case TRACE:
        req = new HttpTrace(url);
        break;

    default:
        throw Err.notExpected();
    }
    return req;
}