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.dataconservancy.dcs.ingest.client.impl.HttpDepositDocument.java

public String getMimeType() {
    if (headers == null) {
        poll(new HttpHead(docUrl));
    }/*from   ww  w. j  a va 2  s . com*/

    for (Header h : headers) {
        if (h.getName().equals(HttpHeaderUtil.CONTENT_TYPE)) {
            return h.getValue();
        }
    }

    logger.warn("Server did not specify content type.  Using default");
    return "application/octet-stream";
}

From source file:com.coroptis.coidi.rp.services.impl.DiscoveryProcessorYadis.java

private DiscoveryResult doHead(String userSuppliedId) throws ClientProtocolException, IOException {
    logger.debug("trying HEAD at '" + userSuppliedId + "'");
    HttpClient httpClient = httpService.getHttpClient();
    HttpHead httpHead = new HttpHead(userSuppliedId);
    httpHead.setHeader("Accept", "application/xrds+xml");
    HttpResponse response = httpClient.execute(httpHead);
    if (HttpServletResponse.SC_OK == response.getStatusLine().getStatusCode()) {
        Header header = response.getFirstHeader("X-XRDS-Location");
        if (header == null) {
            return doGet(userSuppliedId);
        } else {/*  ww  w  .ja  v a 2 s  .  c  o  m*/
            return discoverySupport.getXrdsDocument(header.getValue(), userSuppliedId);
        }
    } else {
        logger.info("OpendID provider response for YADIS HEAD request is:" + response.toString());
        return null;
    }
}

From source file:com.aliyun.oss.common.comm.HttpRequestFactory.java

public HttpRequestBase createHttpRequest(ServiceClient.Request request, ExecutionContext context) {
    String uri = request.getUri();
    HttpRequestBase httpRequest;/* w w w . j ava 2 s . c o  m*/
    HttpMethod method = request.getMethod();
    if (method == HttpMethod.POST) {
        HttpPost postMethod = new HttpPost(uri);

        if (request.getContent() != null) {
            postMethod.setEntity(new RepeatableInputStreamEntity(request));
        }

        httpRequest = postMethod;
    } else if (method == HttpMethod.PUT) {
        HttpPut putMethod = new HttpPut(uri);

        if (request.getContent() != null) {
            if (request.isUseChunkEncoding()) {
                putMethod.setEntity(buildChunkedInputStreamEntity(request));
            } else {
                putMethod.setEntity(new RepeatableInputStreamEntity(request));
            }
        }

        httpRequest = putMethod;
    } else if (method == HttpMethod.GET) {
        httpRequest = new HttpGet(uri);
    } else if (method == HttpMethod.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (method == HttpMethod.HEAD) {
        httpRequest = new HttpHead(uri);
    } else if (method == HttpMethod.OPTIONS) {
        httpRequest = new HttpOptions(uri);
    } else {
        throw new ClientException("Unknown HTTP method name: " + method.toString());
    }

    configureRequestHeaders(request, context, httpRequest);

    return httpRequest;
}

From source file:de.unirostock.sems.cbarchive.web.importer.HttpImporter.java

private boolean checkFile() throws ImporterException {

    try {/*  ww w. jav a 2  s  .co  m*/
        HttpResponse headResponse = client.execute(new HttpHead(remoteUrl));

        // check if file exists
        if (headResponse.getStatusLine().getStatusCode() != 200) {
            LOGGER.error(headResponse.getStatusLine().getStatusCode(), " ",
                    headResponse.getStatusLine().getReasonPhrase(), " while check ", remoteUrl);
            throw new ImporterException(String.valueOf(headResponse.getStatusLine().getStatusCode()) + " "
                    + headResponse.getStatusLine().getReasonPhrase() + " while check");
        }

        // check if file is in the Quota range
        Header contentLengthHeader = headResponse.getFirstHeader("Content-Length");

        // check if Content-Size header is set
        if (contentLengthHeader != null && contentLengthHeader.getValue() != null
                && contentLengthHeader.getValue().isEmpty() == false) {
            length = Long.valueOf(contentLengthHeader.getValue());
        } else {
            LOGGER.warn("Remote file ", remoteUrl, " does not provide Content-Length");
            throw new ImporterException("Remote file does not provide Content-Length");
        }

        // compares this header with the quota
        if (user != null)
            checkQuotas();

    } catch (IOException e) {
        LOGGER.error(e, "Exception while check file from ", remoteUrl);
        throw new ImporterException("Exception while check remote file", e);
    }

    return true;
}

From source file:org.bedework.util.http.HttpUtil.java

public static CloseableHttpResponse doHead(final CloseableHttpClient cl, final URI uri, final Headers hdrs,
        final String acceptContentType) throws IOException {
    final Headers headers = ensureHeaders(hdrs);

    if (acceptContentType != null) {
        headers.add("Accept", acceptContentType);
    }/* ww w . j  a v a  2  s. com*/

    final HttpHead httphead = new HttpHead(uri);

    httphead.setHeaders(headers.asArray());

    return cl.execute(httphead);
}

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

@Test
public void sendHttpHead() throws IOException {
    connection = null;//from  w w  w  .  j a v a2  s .  c  o  m
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
    HttpHead head = new HttpHead(DefaultServer.getDefaultServerURL() + "/path");
    TestHttpClient client = new TestHttpClient();
    try {
        generateMessage(1);
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals(message, HttpClientUtils.readResponse(result));
        result = client.execute(head);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("", HttpClientUtils.readResponse(result));

        generateMessage(1000);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals(message, HttpClientUtils.readResponse(result));
        result = client.execute(head);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("", HttpClientUtils.readResponse(result));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:net.atoom.android.tt2.HttpConnection.java

public synchronized boolean isPageModified(final String pageUrl, final String eTag) {
    HttpHead httpUriRequest = new HttpHead(pageUrl);
    try {/*from  w ww .  j a  v a2  s.  c o  m*/
        HttpResponse httpResponse = myHttpClient.execute(httpUriRequest);
        if (httpResponse.getStatusLine().getStatusCode() != HTTP_OK) {
            if (LogBridge.isLoggable())
                LogBridge.w("Invalid statuscode for: " + pageUrl);
            return false;
        }
        Header eTagHeader = httpResponse.getFirstHeader(ETAG_HEADER);
        if (eTagHeader != null && eTagHeader.getValue().equals(eTag)) {
            if (LogBridge.isLoggable())
                LogBridge.i("Page not modified: " + pageUrl + " (" + eTag + ")");
            return true;
        }
    } catch (ClientProtocolException e) {
        if (LogBridge.isLoggable())
            LogBridge.w("Failed to check page: " + e.getMessage());
    } catch (IOException e) {
        if (LogBridge.isLoggable())
            LogBridge.w("Failed to check page: " + e.getMessage());
    }
    if (LogBridge.isLoggable())
        LogBridge.i("Page is modified: " + pageUrl + "/ (" + eTag + ")");
    return false;
}

From source file:org.jboss.as.test.integration.web.security.servlet.methods.DenyUncoveredHttpMethodsTestCase.java

@Test
public void testHeadMethod() throws Exception {
    HttpHead httpHead = new HttpHead(getURL());
    HttpResponse response = getHttpResponse(httpHead);

    assertThat(statusCodeOf(response), is(HttpServletResponse.SC_UNAUTHORIZED));
}

From source file:com.mogoweb.browser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    //        HttpHost httpHost;
    //        try {
    //            httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    //            if (httpHost != null) {
    //                ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    //            }
    //        } catch (IllegalArgumentException ex) {
    //            Log.e(LOGTAG,"Download failed: " + ex);
    //            client.close();
    //            return;
    //        }/*w  ww  .j a va  2  s .com*/
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mimeType = newMimeType;
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:org.wso2.carbon.apimgt.impl.utils.CommonUtil.java

/**
 * Validate the backend by sending HTTP HEAD
 *
 * @param urlVal - backend URL//  w w  w  . j  av  a2s. co  m
 * @return - status of HTTP HEAD Request to backend
 */
public static String sendHttpHEADRequest(String urlVal) {

    String response = "error while connecting";

    HttpClient client = new DefaultHttpClient();
    HttpHead head = new HttpHead(urlVal);
    client.getParams().setParameter("http.socket.timeout", 4000);
    client.getParams().setParameter("http.connection.timeout", 4000);

    if (System.getProperty(APIConstants.HTTP_PROXY_HOST) != null
            && System.getProperty(APIConstants.HTTP_PROXY_PORT) != null) {
        if (log.isDebugEnabled()) {
            log.debug("Proxy configured, hence routing through configured proxy");
        }
        String proxyHost = System.getProperty(APIConstants.HTTP_PROXY_HOST);
        String proxyPort = System.getProperty(APIConstants.HTTP_PROXY_PORT);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(proxyHost, new Integer(proxyPort)));
    }

    try {
        HttpResponse httpResponse = client.execute(head);
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        //If the endpoint doesn't support HTTP HEAD or if status code is < 400
        if (statusCode == 405 || statusCode % 100 < 4) {
            if (log.isDebugEnabled() && statusCode == 405) {
                log.debug("Endpoint doesn't support HTTP HEAD");
            }
            response = "success";
        }
    } catch (IOException e) {
        // sending a default error message.
        log.error("Error occurred while connecting backend : " + urlVal + ", reason : " + e.getMessage(), e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return response;
}