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.lokra.seaweedfs.core.VolumeWrapper.java

/**
 * Check file is exist.//from   w  w w . ja v  a 2s .c  o m
 *
 * @param url Server url.
 * @param fid File id.
 * @return If file is exist that result is true.
 * @throws IOException Http connection is fail or server response within some error message.
 */
boolean checkFileExist(String url, String fid) throws IOException {
    HttpHead request = new HttpHead(url + "/" + fid);
    final int statusCode = connection.fetchStatusCodeByRequest(request);
    try {
        convertResponseStatusToException(statusCode, url, fid, false, true, false, false);
        return true;
    } catch (SeaweedfsFileNotFoundException e) {
        return false;
    }
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public HootResult synchronousExecute(HootRequest request) {

    HttpRequestBase requestBase = null;/* ww  w. ja  v a2 s. c om*/
    HootResult result = request.getResult();
    try {
        String uri = request.buildUri().toString();
        switch (request.getOperation()) {
        case DELETE:
            requestBase = new HttpDelete(uri);
            break;
        case GET:
            requestBase = new HttpGet(uri);
            break;
        case PUT:
            HttpPut put = new HttpPut(uri);
            put.setEntity(getEntity(request));
            requestBase = put;
            break;
        case POST:
            HttpPost post = new HttpPost(uri);
            post.setEntity(getEntity(request));
            requestBase = post;
            break;
        case HEAD:
            requestBase = new HttpHead(uri);
            break;
        }
    } catch (UnsupportedEncodingException e1) {
        result.setException(e1);
        e1.printStackTrace();
        return result;
    } catch (IOException e) {
        result.setException(e);
        e.printStackTrace();
        return result;
    }

    synchronized (mRequestBaseMap) {
        mRequestBaseMap.put(request, requestBase);
    }
    if (request.getHeaders() != null && request.getHeaders().size() > 0) {
        for (Object propertyKey : request.getHeaders().keySet()) {
            requestBase.addHeader((String) propertyKey, (String) request.getHeaders().get(propertyKey));
        }
    }

    InputStream is = null;
    try {
        Log.v(TAG, "URI: [" + requestBase.getURI().toString() + "]");
        HttpResponse response = mClient.execute(requestBase);

        if (response != null) {
            result.setResponseCode(response.getStatusLine().getStatusCode());
            Map<String, List<String>> headers = new HashMap<String, List<String>>();
            for (Header header : response.getAllHeaders()) {
                List<String> values = new ArrayList<String>();
                values.add(header.getValue());
                headers.put(header.getName(), values);
            }
            result.setHeaders(headers);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                result.setResponseStream(new BufferedInputStream(is));
                request.deserializeResult();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        result.setException(e);
    } finally {
        requestBase = null;
        synchronized (mRequestBaseMap) {
            mRequestBaseMap.remove(request);
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

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

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

    Header contentLength = response.getFirstHeader("Content-Length");
    return Long.parseLong(contentLength.getValue());
}

From source file:neal.http.impl.httpstack.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from   w  w w .j  av a  2s. c  o  m
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws HttpErrorCollection.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.meplato.store2.ApacheHttpClient.java

/**
 * Execute runs a HTTP request/response with an API endpoint.
 *
 * @param method      the HTTP method, e.g. POST or GET
 * @param uriTemplate the URI template according to RFC 6570
 * @param parameters  the query string parameters
 * @param headers     the key/value pairs for the HTTP header
 * @param body        the body of the request or {@code null}
 * @return the HTTP response encapsulated by {@link Response}.
 * @throws ServiceException if e.g. the service is unavailable.
 *//*from   w  w  w  .ja  v a  2 s .  c  o  m*/
@Override
public Response execute(String method, String uriTemplate, Map<String, Object> parameters,
        Map<String, String> headers, Object body) throws ServiceException {
    // URI template parameters
    String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters);

    // Body
    HttpEntity requestEntity = null;
    if (body != null) {
        Gson gson = getSerializer();
        try {
            requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8")
                    .setContentType(ContentType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new ServiceException("Error serializing body", null, e);
        }
    }

    // Do HTTP request
    HttpRequestBase httpRequest = null;
    if (method.equalsIgnoreCase("GET")) {
        httpRequest = new HttpGet(url);
    } else if (method.equalsIgnoreCase("POST")) {
        HttpPost httpPost = new HttpPost(url);
        if (requestEntity != null) {
            httpPost.setEntity(requestEntity);
        }
        httpRequest = httpPost;
    } else if (method.equalsIgnoreCase("PUT")) {
        HttpPut httpPut = new HttpPut(url);
        if (requestEntity != null) {
            httpPut.setEntity(requestEntity);
        }
        httpRequest = httpPut;
    } else if (method.equalsIgnoreCase("DELETE")) {
        httpRequest = new HttpDelete(url);
    } else if (method.equalsIgnoreCase("PATCH")) {
        HttpPatch httpPatch = new HttpPatch(url);
        if (requestEntity != null) {
            httpPatch.setEntity(requestEntity);
        }
        httpRequest = httpPatch;
    } else if (method.equalsIgnoreCase("HEAD")) {
        httpRequest = new HttpHead(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        httpRequest = new HttpOptions(url);
    } else {
        throw new ServiceException("Invalid HTTP method: " + method, null, null);
    }

    // Headers
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }
    httpRequest.setHeader("Accept", "application/json");
    httpRequest.setHeader("Accept-Charset", "utf-8");
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");
    httpRequest.setHeader("User-Agent", USER_AGENT);

    try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) {
        Response response = new ApacheHttpResponse(httpResponse);
        int statusCode = response.getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            return response;
        }
        throw ServiceException.fromResponse(response);
    } catch (ClientProtocolException e) {
        throw new ServiceException("Client Protocol Exception", null, e);
    } catch (IOException e) {
        throw new ServiceException("IO Exception", null, e);
    }
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

@Override
public void run() {
    if (!ApplicationState.getInstance().runningProperty().get()) {
        response.setException(new Exception(ApplicationState.getMessage(ACTIVITY_TERMINATED)));
        return;/*from   ww  w  . jav a2s  . c o m*/
    }
    response.started().set(true);
    response.updateProgress(0.5);

    if (action.getDelay() > 0) {
        try {
            Thread.sleep(action.getDelay());
        } catch (InterruptedException ex) {
            response.setException(ex);
            return;
        }
    }

    HttpUriRequest request;
    try {
        switch (httpMethod) {
        case GET:
            request = new HttpGet(getURL());
            break;
        case HEAD:
            request = new HttpHead(getURL());
            break;
        case DELETE:
            request = new HttpDelete(getURL());
            break;
        case POST:
            request = new HttpPost(getURL());
            addPostParams((HttpPost) request);
            break;
        case PUT:
            request = new HttpPut(getURL());
            ((HttpPut) request).setEntity(new FileEntity(new File(putFile)));
            break;
        default:
            throw new UnsupportedOperationException(
                    ApplicationState.getMessage(UNSUPPORTED_METHOD_ERROR) + ": " + httpMethod.name());
        }

        addHeaders(request);
        Optional<Exception> ex = processor.apply((CloseableHttpClient client) -> {
            try (CloseableHttpResponse httpResponse = client.execute(request, ConnectionManager.getContext())) {
                response.processHttpResponse(httpResponse, action.getResultType());
                EntityUtils.consume(httpResponse.getEntity());
                return Optional.empty();
            } catch (Exception e) {
                return Optional.of(e);
            }
        });
        if (ex.isPresent()) {
            throw ex.get();
        }
    } catch (Exception ex) {
        Logger.getLogger(ActionRunner.class.getName()).log(Level.SEVERE, null, ex);
        response.setException(ex);
    } finally {
        response.updateProgress(1);
    }
}

From source file:org.doctester.testbrowser.TestBrowserImpl.java

private Response makeHeadGetOrDeleteRequest(Request request) {

    Response response;/*from  ww w.  j  a v  a2  s . c  o m*/

    org.apache.http.HttpResponse apacheHttpClientResponse;

    try {

        HttpUriRequest apacheHttpRequest;

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        if (GET.equalsIgnoreCase(request.httpRequestType)) {

            apacheHttpRequest = new HttpGet(request.uri);

        } else if (DELETE.equalsIgnoreCase(request.httpRequestType)) {

            apacheHttpRequest = new HttpDelete(request.uri);

        } else {

            apacheHttpRequest = new HttpHead(request.uri);

        }

        if (request.headers != null) {

            // add all headers
            for (Entry<String, String> header : request.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }

        }

        setHandleRedirect(apacheHttpRequest, request.followRedirects);

        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);

        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        if (apacheHttpRequest instanceof HttpRequestBase) {
            ((HttpRequestBase) apacheHttpRequest).releaseConnection();
        }

    } catch (IOException e) {
        logger.error("Fatal problem creating GET or DELETE request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;
}

From source file:org.graphity.core.util.jena.DatasetGraphAccessorHTTP.java

private boolean doHead(String url) {
    HttpUriRequest httpHead = new HttpHead(url);
    try {/* w w  w  .j  a  v  a  2  s .c  o m*/
        HttpOp.execHttpHead(url, WebContent.defaultGraphAcceptHeader, noResponse, null, null,
                this.authenticator);
        return true;
    } catch (HttpException ex) {
        if (ex.getResponseCode() == HttpSC.NOT_FOUND_404)
            return false;
        throw ex;
    }
}

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

protected AbstractHttpMessage getMethod(String httpMethod, String urlStr) {
    AbstractHttpMessage method = null;// w  ww.  ja va2 s.  c o  m
    if (httpMethod.equals("GET")) {
        method = new HttpGet(urlStr);
    } else if (httpMethod.equals("POST")) {
        method = new HttpPost(urlStr);
    } else if (httpMethod.equals("PUT")) {
        method = new HttpPut(urlStr);
    } else if (httpMethod.equals("DELETE")) {
        method = new HttpDelete(urlStr);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpHead(urlStr);
    } else if (httpMethod.equals("OPTIONS")) {
        method = new HttpOptions(urlStr);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpTrace(urlStr);
    } else {
        return null;
    }
    return method;
}