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

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

Introduction

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

Prototype

public HeadMethod(String paramString) 

Source Link

Usage

From source file:org.apache.webdav.ant.Utils.java

/**
 * Returns <code>true</code> if the resource given as URL does exist.
 * @param client//www  .j a v a  2  s .  c o  m
 * @param httpURL
 * @return <code>true</code>if the resource exists
 * @throws IOException
 * @throws HttpException
 */
public static boolean resourceExists(HttpClient client, HttpURL httpURL) throws IOException, HttpException {
    HeadMethod head = new HeadMethod(httpURL.getEscapedURI());
    head.setFollowRedirects(true);
    int status = client.executeMethod(head);

    switch (status) {
    case WebdavStatus.SC_OK:
        return true;
    case WebdavStatus.SC_NOT_FOUND:
        return false;
    default:
        HttpException ex = new HttpException();
        ex.setReasonCode(status);
        ex.setReason(head.getStatusText());
        throw ex;
    }
}

From source file:org.apache.webdav.lib.WebdavResource.java

/**
 * Execute the HEAD method for the given path.
 *
 * @param path the server relative path of the resource to request
 * @return true if the method is succeeded.
 * @exception HttpException// ww  w  .jav  a 2 s .c  o  m
 * @exception IOException
 */
public boolean headMethod(String path) throws HttpException, IOException {

    setClient();
    HeadMethod method = new HeadMethod(URIUtil.encodePathQuery(path));

    generateTransactionHeader(method);
    generateAdditionalHeaders(method);
    int statusCode = client.executeMethod(method);

    setStatusCode(statusCode);
    return (statusCode >= 200 && statusCode < 300) ? true : false;
}

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

/**
 * This will drive several different requests that interact with the
 * Departments resource class./* ww  w . j a v  a  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.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;/*from  w w w  . j ava  2  s.co  m*/
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        String expect = request.getHeaders().getFirstValue("Expect");
        if (expect != null && expect.equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    Collection<Cookie> cookies = request.getCookies();
    if (isNonEmpty(cookies)) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    String ua = request.getHeaders().getFirstValue("User-Agent");
    if (ua != null) {
        method.setRequestHeader("User-Agent", ua);
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class, config));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.attribyte.api.http.impl.commons.Commons3Client.java

@Override
public Response send(Request request, RequestOptions options) throws IOException {

    HttpMethod method = null;// w  w w .  jav a2 s . com

    switch (request.getMethod()) {
    case GET:
        method = new GetMethod(request.getURI().toString());
        method.setFollowRedirects(options.followRedirects);
        break;
    case DELETE:
        method = new DeleteMethod(request.getURI().toString());
        break;
    case HEAD:
        method = new HeadMethod(request.getURI().toString());
        method.setFollowRedirects(options.followRedirects);
        break;
    case POST:
        method = new PostMethod(request.getURI().toString());
        if (request.getBody() != null) {
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray());
            ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        } else {
            PostMethod postMethod = (PostMethod) method;
            Collection<Parameter> parameters = request.getParameters();
            for (Parameter parameter : parameters) {
                String[] values = parameter.getValues();
                for (String value : values) {
                    postMethod.addParameter(parameter.getName(), value);
                }
            }
        }
        break;
    case PUT:
        method = new PutMethod(request.getURI().toString());
        if (request.getBody() != null) {
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray());
            ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        }
        break;
    }

    if (userAgent != null && Strings.isNullOrEmpty(request.getHeaderValue("User-Agent"))) {
        method.setRequestHeader("User-Agent", userAgent);
    }

    Collection<Header> headers = request.getHeaders();
    for (Header header : headers) {
        String[] values = header.getValues();
        for (String value : values) {
            method.setRequestHeader(header.getName(), value);
        }
    }

    int responseCode;
    InputStream is = null;

    try {
        responseCode = httpClient.executeMethod(method);
        is = method.getResponseBodyAsStream();
        if (is != null) {
            byte[] body = Request.bodyFromInputStream(is, options.maxResponseBytes);
            ResponseBuilder builder = new ResponseBuilder();
            builder.setStatusCode(responseCode);
            builder.addHeaders(getMap(method.getResponseHeaders()));
            return builder.setBody(body.length != 0 ? body : null).create();
        } else {
            ResponseBuilder builder = new ResponseBuilder();
            builder.setStatusCode(responseCode);
            builder.addHeaders(getMap(method.getResponseHeaders()));
            return builder.create();
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                //Ignore
            }
        }
        method.releaseConnection();
    }
}

From source file:org.bibsonomy.rest.client.worker.impl.HeadWorker.java

@Override
protected HeadMethod getMethod(String url, String requestBody) {
    final HeadMethod head = new HeadMethod(url);
    head.setFollowRedirects(true);/*from   w ww. j  a v a  2  s  .  c  om*/
    return head;
}

From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI./*from  w  w  w. j a  v  a 2 s.c  om*/
 * @return a new HttpMethod subclass.
 */
protected HttpMethod getMethod(HTTPMethod method, URI requestURI) {
    if (CONNECT.equals(method)) {
        HostConfiguration config = new HostConfiguration();
        config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
        return new ConnectMethod(config);
    } else if (DELETE.equals(method)) {
        return new DeleteMethod(requestURI.toString());
    } else if (GET.equals(method)) {
        return new GetMethod(requestURI.toString());
    } else if (HEAD.equals(method)) {
        return new HeadMethod(requestURI.toString());
    } else if (OPTIONS.equals(method)) {
        return new OptionsMethod(requestURI.toString());
    } else if (POST.equals(method)) {
        return new PostMethod(requestURI.toString());
    } else if (PUT.equals(method)) {
        return new PutMethod(requestURI.toString());
    } else if (TRACE.equals(method)) {
        return new TraceMethod(requestURI.toString());
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
}

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  ww  .j  a va 2 s .  com*/
    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.crosswire.common.util.WebResource.java

/**
 * Determine the size of this WebResource.
 * <p>Note that the http client may read the entire file to determine this.</p>
 *
 * @return the size of the file//w ww .j  av a  2 s .co m
 */
public int getSize() {
    HttpMethod method = new HeadMethod(uri.getPath());

    try {
        // Execute the method.
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            return new HttpURLConnection(method, NetUtil.toURL(uri)).getContentLength();
        }
        String reason = HttpStatus.getStatusText(status);
        Reporter.informUser(this, Msg.MISSING_FILE, new Object[] { reason + ':' + uri.getPath() });
    } catch (IOException e) {
        return 0;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return 0;
}

From source file:org.crosswire.common.util.WebResource.java

/**
 * Determine the last modified date of this WebResource.
 * <p>Note that the http client may read the entire file.</p>
 *
 * @return the last mod date of the file
 *///from   w w w.j a v  a  2  s .  c o m
public long getLastModified() {
    HttpMethod method = new HeadMethod(uri.getPath());

    try {
        // Execute the method.
        if (client.executeMethod(method) == HttpStatus.SC_OK) {
            return new HttpURLConnection(method, NetUtil.toURL(uri)).getLastModified();
        }
    } catch (IOException e) {
        return new Date().getTime();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return new Date().getTime();
}