Example usage for org.apache.commons.httpclient.methods HeadMethod getResponseHeaders

List of usage examples for org.apache.commons.httpclient.methods HeadMethod getResponseHeaders

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods HeadMethod getResponseHeaders.

Prototype

@Override
public Header[] getResponseHeaders() 

Source Link

Document

Returns an array of the response headers that the HTTP method currently has in the order in which they were read.

Usage

From source file:com.owncloud.android.operations.ExistenceCheckOperation.java

@Override
protected RemoteOperationResult run(WebdavClient client) {
    if (!isOnline()) {
        return new RemoteOperationResult(RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION);
    }//from  w  w  w. j  a va 2  s.com
    RemoteOperationResult result = null;
    HeadMethod head = null;
    try {
        head = new HeadMethod(client.getBaseUri() + WebdavUtils.encodePath(mPath));
        int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
        client.exhaustResponse(head.getResponseBodyAsStream());
        boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent)
                || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
        result = new RemoteOperationResult(success, status, head.getResponseHeaders());
        Log_OC.d(TAG,
                "Existence check for " + client.getBaseUri() + WebdavUtils.encodePath(mPath) + " targeting for "
                        + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status "
                        + status + (!success ? "(FAIL)" : ""));

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG,
                "Existence check for " + client.getBaseUri() + WebdavUtils.encodePath(mPath) + " targeting for "
                        + (mSuccessIfAbsent ? " absence " : " existence ") + ": " + result.getLogMessage(),
                result.getException());

    } finally {
        if (head != null)
            head.releaseConnection();
    }
    return result;
}

From source file:com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    if (!isOnline()) {
        return new RemoteOperationResult(RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION);
    }//w  w w  . j  ava  2  s. c  o m
    RemoteOperationResult result = null;
    HeadMethod head = null;
    try {
        head = new HeadMethod(client.getWebdavUri() + WebdavUtils.encodePath(mPath));
        int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
        client.exhaustResponse(head.getResponseBodyAsStream());
        boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent)
                || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
        result = new RemoteOperationResult(success, status, head.getResponseHeaders());
        Log_OC.d(TAG,
                "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath)
                        + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ")
                        + "finished with HTTP status " + status + (!success ? "(FAIL)" : ""));

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG,
                "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath)
                        + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + ": "
                        + result.getLogMessage(),
                result.getException());

    } finally {
        if (head != null)
            head.releaseConnection();
    }
    return result;
}

From source file:com.sa.npopa.samples.hbase.rest.client.Client.java

/**
 * Send a HEAD request //from   w ww . j  a  v  a 2  s .c  o m
 * @param cluster the cluster definition
 * @param path the path or URI
 * @param headers the HTTP headers to include in the request
 * @return a Response object with response detail
 * @throws IOException
 */
public Response head(Cluster cluster, String path, Header[] headers) throws IOException {
    HeadMethod method = new HeadMethod();
    try {
        int code = execute(cluster, method, null, path);
        headers = method.getResponseHeaders();
        return new Response(code, headers, null);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cerema.cloud2.lib.resources.files.ExistenceCheckRemoteOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    HeadMethod head = null;
    boolean previousFollowRedirects = client.getFollowRedirects();
    try {/*from   w  w  w.  java  2  s  .c o  m*/
        head = new HeadMethod(client.getWebdavUri() + WebdavUtils.encodePath(mPath));
        client.setFollowRedirects(false);
        int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
        if (previousFollowRedirects) {
            mRedirectionPath = client.followRedirection(head);
            status = mRedirectionPath.getLastStatus();
        }
        client.exhaustResponse(head.getResponseBodyAsStream());
        boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent)
                || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
        result = new RemoteOperationResult(success, status, head.getResponseHeaders());
        Log_OC.d(TAG,
                "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath)
                        + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ")
                        + "finished with HTTP status " + status + (!success ? "(FAIL)" : ""));

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG,
                "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath)
                        + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + ": "
                        + result.getLogMessage(),
                result.getException());

    } finally {
        if (head != null)
            head.releaseConnection();
        client.setFollowRedirects(previousFollowRedirects);
    }
    return result;
}

From source file:opendap.noaa_s3.RemoteResource.java

/**
 *
 * @return//from ww w .j  av a  2s . c  o  m
 * @throws IOException
 * @throws JDOMException
 */
public void updateResponseHeaders() {

    log.debug("updateResponseHeaders() - Retrieving HTTP HEAD for '{}'", _resourceUrl);

    // Go get the HEAD for the catalog:
    HttpClient httpClient = new HttpClient();
    HeadMethod headReq = new HeadMethod(_resourceUrl);

    try {
        int statusCode = httpClient.executeMethod(headReq);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Unable to HEAD s3 object: " + _resourceUrl);
        } else {

            _responseHeaders = headReq.getResponseHeaders();

        }

    } catch (Exception e) {
        log.error("Unable to HEAD the resource: {} Error Msg: {}", _resourceUrl, e.getMessage());
    }
}

From source file:org.apache.hadoop.fs.swift.http.SwiftRestClient.java

/**
 * Issue a head request/*  ww  w.  jav  a 2 s .  c  o  m*/
 * @param path path to query
 * @param requestHeaders request header
 * @return the response headers. This may be an empty list
 * @throws IOException IO problems
 * @throws FileNotFoundException if there is nothing at the end
 */
public Header[] headRequest(SwiftObjectPath path, final Header... requestHeaders) throws IOException {
    preRemoteCommand("headRequest");
    return perform(pathToURI(path), new HeadMethodProcessor<Header[]>() {
        @Override
        public Header[] extractResult(HeadMethod method) throws IOException {
            if (method.getStatusCode() == SC_NOT_FOUND) {
                throw new FileNotFoundException("Not Found " + method.getURI());
            }

            return method.getResponseHeaders();
        }

        @Override
        protected void setup(HeadMethod method) throws SwiftInternalStateException {
            setHeaders(method, requestHeaders);
        }
    });
}

From source file:org.apache.wink.itest.contextresolver.DepartmentTest.java

/**
 * This will drive several different requests that interact with the
 * Departments resource class.//from  ww w . j  ava  2  s.c  o m
 */
public void testDepartmentsResourceJAXB() throws Exception {
    PostMethod postMethod = null;
    GetMethod getAllMethod = null;
    GetMethod getOneMethod = null;
    HeadMethod headMethod = null;
    DeleteMethod deleteMethod = null;
    try {

        // make sure everything is clear before testing
        DepartmentDatabase.clearEntries();

        // create a new Department
        Department newDepartment = new Department();
        newDepartment.setDepartmentId("1");
        newDepartment.setDepartmentName("Marketing");
        JAXBContext context = JAXBContext
                .newInstance(new Class<?>[] { Department.class, DepartmentListWrapper.class });
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(newDepartment, sw);
        HttpClient client = new HttpClient();
        postMethod = new PostMethod(getBaseURI());
        RequestEntity reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml");
        postMethod.setRequestEntity(reqEntity);
        client.executeMethod(postMethod);

        newDepartment = new Department();
        newDepartment.setDepartmentId("2");
        newDepartment.setDepartmentName("Sales");
        sw = new StringWriter();
        marshaller.marshal(newDepartment, sw);
        client = new HttpClient();
        postMethod = new PostMethod(getBaseURI());
        reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml");
        postMethod.setRequestEntity(reqEntity);
        client.executeMethod(postMethod);

        // now let's get the list of Departments that we just created
        // (should be 2)
        client = new HttpClient();
        getAllMethod = new GetMethod(getBaseURI());
        client.executeMethod(getAllMethod);
        byte[] bytes = getAllMethod.getResponseBody();
        assertNotNull(bytes);
        InputStream bais = new ByteArrayInputStream(bytes);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object obj = unmarshaller.unmarshal(bais);
        assertTrue(obj instanceof DepartmentListWrapper);
        DepartmentListWrapper wrapper = (DepartmentListWrapper) obj;
        List<Department> dptList = wrapper.getDepartmentList();
        assertNotNull(dptList);
        assertEquals(2, dptList.size());

        // now get a specific Department that was created
        client = new HttpClient();
        getOneMethod = new GetMethod(getBaseURI() + "/1");
        client.executeMethod(getOneMethod);
        bytes = getOneMethod.getResponseBody();
        assertNotNull(bytes);
        bais = new ByteArrayInputStream(bytes);
        obj = unmarshaller.unmarshal(bais);
        assertTrue(obj instanceof Department);
        Department dept = (Department) obj;
        assertEquals("1", dept.getDepartmentId());
        assertEquals("Marketing", dept.getDepartmentName());

        // let's send a Head request for both an existent and non-existent
        // resource
        // we are testing to see if header values being set in the resource
        // implementation
        // are sent back appropriately
        client = new HttpClient();
        headMethod = new HeadMethod(getBaseURI() + "/3");
        client.executeMethod(headMethod);
        assertNotNull(headMethod.getResponseHeaders());
        Header header = headMethod.getResponseHeader("unresolved-id");
        assertNotNull(header);
        assertEquals("3", header.getValue());
        headMethod.releaseConnection();

        // now the resource that should exist
        headMethod = new HeadMethod(getBaseURI() + "/1");
        client.executeMethod(headMethod);
        assertNotNull(headMethod.getResponseHeaders());
        header = headMethod.getResponseHeader("resolved-id");
        assertNotNull(header);
        assertEquals("1", header.getValue());

        deleteMethod = new DeleteMethod(getBaseURI() + "/1");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());

        deleteMethod = new DeleteMethod(getBaseURI() + "/2");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        if (getAllMethod != null) {
            getAllMethod.releaseConnection();
        }
        if (getOneMethod != null) {
            getOneMethod.releaseConnection();
        }
        if (headMethod != null) {
            headMethod.releaseConnection();
        }
        if (deleteMethod != null) {
            deleteMethod.releaseConnection();
        }
    }
}

From source file:org.apache.wink.itest.methodannotations.HttpMethodTest.java

/**
 * Tests that a HEAD request can be sent to resource containing only a GET
 * method./*from ww  w .  jav  a  2 s  .c o m*/
 */
public void testHEADRequest() {
    try {
        HeadMethod httpMethod = new HeadMethod();
        httpMethod.setURI(new URI(BASE_URI, false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertEquals(200, result);
            assertEquals(null, responseBody);
            Header[] headers = httpMethod.getResponseHeaders();
            assertNotNull(headers);
            assertTrue("Response for HEAD request contained no headers", headers.length > 0);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.collectionspace.services.client.test.ServiceLayerTest.java

@Test
public void headSupported() {
    if (logger.isDebugEnabled()) {
        logger.debug(BaseServiceTest.testBanner("headSupported", CLASS_NAME));
    }//from  w  w w .ja  va2s . c  o  m
    String url = serviceClient.getBaseURL() + "intakes";
    HeadMethod method = new HeadMethod(url);
    try {
        int statusCode = httpClient.executeMethod(method);
        Assert.assertEquals(method.getResponseBody(), null, "expected null");
        if (logger.isDebugEnabled()) {
            logger.debug("headSupported url=" + url + " status=" + statusCode);
            for (Header h : method.getResponseHeaders()) {
                logger.debug("headSupported header name=" + h.getName() + " value=" + h.getValue());
            }
        }
        Assert.assertEquals(statusCode, HttpStatus.SC_OK, "expected " + HttpStatus.SC_OK);
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
    } catch (IOException e) {
        logger.error("Fatal transport error", e);
    } catch (Exception e) {
        logger.error("unknown exception ", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

public int getHttpStatus(String url) {
    String encodedUrl = getEncodedUrl(url);
    HttpClient httpClient = getHttpClient(encodedUrl);
    HeadMethod head = new HeadMethod(encodedUrl);
    try {//w  ww .j  a va 2s.co m
        LOGGER.debug("executing head request to retrieve page status on " + head.getURI());
        int status = httpClient.executeMethod(head);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("received " + status + " from head request");
            for (Header h : head.getResponseHeaders()) {
                LOGGER.debug("header : " + h.toExternalForm());
            }
        }

        return status;
    } catch (UnknownHostException uhe) {
        LOGGER.warn("UnknownHostException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IllegalArgumentException iae) {
        LOGGER.warn("IllegalArgumentException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IOException ioe) {
        LOGGER.warn("IOException on " + encodedUrl);
        ioe.fillInStackTrace();
        return HttpStatus.SC_NOT_FOUND;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        head.releaseConnection();
    }
}