org.apache.commons.httpclient.methods.HeadMethod Java Examples

The following examples show how to use org.apache.commons.httpclient.methods.HeadMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpResource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public boolean exists() throws ResourceException {
    HeadMethod headMethod = new HeadMethod(resourceUrl);
    headMethod.addRequestHeader("Connection", "close");

    try {
        httpClient.executeMethod(headMethod);
        if (headMethod.getStatusCode() != HttpStatus.SC_OK) {
            return false;
        }

        return true;
    } catch (IOException e) {
        throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e);
    } finally {
        headMethod.releaseConnection();
    }
}
 
Example #2
Source File: HttpFileContentInfoFactory.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {

    String contentType = null;
    String contentEncoding = null;

    HeadMethod headMethod;
    try (final HttpFileObject<HttpFileSystem> httpFile = (HttpFileObject<HttpFileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        headMethod = httpFile.getHeadMethod();
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
    final Header header = headMethod.getResponseHeader("content-type");
    if (header != null) {
        final HeaderElement[] element = header.getElements();
        if (element != null && element.length > 0) {
            contentType = element[0].getName();
        }
    }

    contentEncoding = headMethod.getResponseCharSet();

    return new DefaultFileContentInfo(contentType, contentEncoding);
}
 
Example #3
Source File: ApacheHttp31SLR.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
private void acquireLength() throws URISyntaxException, HttpException, IOException {
	HttpMethod head = new HeadMethod(url);
	int code = http.executeMethod(head);
	if(code != 200) {
		throw new IOException("Unable to retrieve from " + url);
	}
	Header lengthHeader = head.getResponseHeader(CONTENT_LENGTH);
	if(lengthHeader == null) {
		throw new IOException("No Content-Length header for " + url);
	}
	String val = lengthHeader.getValue();
	try {
		length = Long.parseLong(val);
	} catch(NumberFormatException e) {
		throw new IOException("Bad Content-Length value " +url+ ": " + val);
	}
}
 
Example #4
Source File: UriUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static void checkUrlExistence(String url) {
    if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) {
        HttpClient httpClient = getHttpClient();
        HeadMethod httphead = new HeadMethod(url);
        try {
            if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) {
                throw new IllegalArgumentException("Invalid URL: " + url);
            }
            if (url.endsWith("metalink") && !checkUrlExistenceMetalink(url)) {
                throw new IllegalArgumentException("Invalid URLs defined on metalink: " + url);
            }
        } catch (HttpException hte) {
            throw new IllegalArgumentException("Cannot reach URL: " + url + " due to: " + hte.getMessage());
        } catch (IOException ioe) {
            throw new IllegalArgumentException("Cannot reach URL: " + url + " due to: " + ioe.getMessage());
        } finally {
            httphead.releaseConnection();
        }
    }
}
 
Example #5
Source File: FileResourceImpl.java    From swift-k with Apache License 2.0 6 votes vote down vote up
public boolean exists(String filename) throws FileResourceException {
    HeadMethod m = new HeadMethod(contact + '/' + filename);
    try {
        int code = client.executeMethod(m);
        try {
            if (code != HttpStatus.SC_OK) {
                return false;
            }
            else {
                return true;
            }
        }
        finally {
            m.releaseConnection();
        }
    }
    catch (Exception e) {
        throw new FileResourceException(e);
    }
}
 
Example #6
Source File: HelloIvy.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String  message = "Hello Ivy!";
    System.out.println("standard message : " + message);
    System.out.println("capitalized by " + WordUtils.class.getName()
        + " : " + WordUtils.capitalizeFully(message));

    HttpClient client = new HttpClient();
    HeadMethod head = new HeadMethod("http://www.ibiblio.org/");
    client.executeMethod(head);

    int status = head.getStatusCode();
    System.out.println("head status code with httpclient: " + status);
    head.releaseConnection();

    System.out.println(
        "now check if httpclient dependency on commons-logging has been realized");
    Class<?> clss = Class.forName("org.apache.commons.logging.Log");
    System.out.println("found logging class in classpath: " + clss);
}
 
Example #7
Source File: Hc3HttpUtils.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Create an HTTP HEAD Method.
 * 
 * @param url URL of the request.
 * @param properties Properties to drive the API.
 * @return HEAD Method
 * @throws URIException Exception if the URL is not correct.
 */
public static HeadMethod createHttpHeadMethod(
    String url,
    Map<String, String> properties) throws URIException {

  // Initialize HEAD Method
  org.apache.commons.httpclient.URI uri = null;
  try {
    uri = new org.apache.commons.httpclient.URI(url, true, "UTF8");
  } catch (URIException e) {
    uri = new org.apache.commons.httpclient.URI(url, false, "UTF8");
  }
  HeadMethod method = new HeadMethod();
  method.setURI(uri);
  method.getParams().setSoTimeout(60000);
  method.getParams().setContentCharset("UTF-8");
  method.setRequestHeader("Accept-Encoding", "gzip");

  // Manager query string
  StringBuilder debugUrl = (DEBUG_URL) ? new StringBuilder("HEAD " + url) : null;
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  if (properties != null) {
    boolean first = true;
    Iterator<Map.Entry<String, String>> iter = properties.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry<String, String> property = iter.next();
      String key = property.getKey();
      String value = property.getValue();
      params.add(new NameValuePair(key, value));
      first = fillDebugUrl(debugUrl, first, key, value);
    }
  }
  if (DEBUG_URL && (debugUrl != null)) {
    debugText(debugUrl.toString());
  }
  NameValuePair[] tmpParams = new NameValuePair[params.size()];
  method.setQueryString(params.toArray(tmpParams));

  return method;
}
 
Example #8
Source File: ApacheHttp31SLR.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
protected String getHeader(String header) throws URISyntaxException, HttpException, IOException {
	HttpMethod head = new HeadMethod(url);
	int code = http.executeMethod(head);
	if(code != 200) {
		throw new IOException("Unable to retrieve from " + url);
	}
	Header theHeader = head.getResponseHeader(header);
	if(theHeader == null) {
		throw new IOException("No " + header + " header for " + url);
	}
	String val = theHeader.getValue();
	return val;
}
 
Example #9
Source File: Worker.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private HttpMethodBase createHttpMethod(String method, String url) {
    switch (method.toUpperCase()) {
        case "HEAD":
            return new HeadMethod(url);
        case "GET":
            return new GetMethod(url);
        default:
            throw new IllegalStateException("Method not yet created");
    }
}
 
Example #10
Source File: ResponseHandlerFactory.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the method being received and created a 
 * suitable ResponseHandler for this method.
 * 
 * @param method Method to handle
 * @return The handler for this response
 * @throws MethodNotAllowedException If no method could be choose this exception is thrown
 */
public static ResponseHandler createResponseHandler(HttpMethod method) throws MethodNotAllowedException {
    if (!AllowedMethodHandler.methodAllowed(method)) {
        throw new MethodNotAllowedException("The method " + method.getName() + " is not in the AllowedHeaderHandler's list of allowed methods.", AllowedMethodHandler.getAllowHeader());
    }
    
    ResponseHandler handler = null;
    if (method.getName().equals("OPTIONS")) {
        handler = new OptionsResponseHandler((OptionsMethod) method);
    } else if (method.getName().equals("GET")) {
        handler = new GetResponseHandler((GetMethod) method);
    } else if (method.getName().equals("HEAD")) {
        handler = new HeadResponseHandler((HeadMethod) method);
    } else if (method.getName().equals("POST")) {
        handler = new PostResponseHandler((PostMethod) method);
    } else if (method.getName().equals("PUT")) {
        handler = new PutResponseHandler((PutMethod) method);
    } else if (method.getName().equals("DELETE")) {
        handler = new DeleteResponseHandler((DeleteMethod) method);
    } else if (method.getName().equals("TRACE")) {
        handler = new TraceResponseHandler((TraceMethod) method);
    } else {
        throw new MethodNotAllowedException("The method " + method.getName() + " was allowed by the AllowedMethodHandler, not by the factory.", handledMethods);
    }

    return handler;
}
 
Example #11
Source File: UriUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static void checkUrlExistence(final String url) {
    if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) {
        final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
        final HeadMethod httphead = new HeadMethod(url);
        try {
            if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) {
                throw new IllegalArgumentException("Invalid URL: " + url);
            }
        } catch (final HttpException hte) {
            throw new IllegalArgumentException("Cannot reach URL: " + url);
        } catch (final IOException ioe) {
            throw new IllegalArgumentException("Cannot reach URL: " + url);
        }
    }
}
 
Example #12
Source File: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public HttpResponse head(final RequestContext rq, Binding cmisBinding, String version, String cmisOperation) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), cmisBinding, version, cmisOperation, null);
    String url = endpoint.getUrl();

    HeadMethod req = new HeadMethod(url.toString());
    return submitRequest(req, rq);
}
 
Example #13
Source File: AbstractHttpClient.java    From alfresco-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpMethod createMethod(Request req) throws IOException
{
    StringBuilder url = new StringBuilder(128);
    url.append(baseUrl);
    url.append("/service/");
    url.append(req.getFullUri());

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if(method.equalsIgnoreCase("GET"))
    {
        GetMethod get = new GetMethod(url.toString());
        httpMethod = get;
        httpMethod.setFollowRedirects(true);
    }
    else if(method.equalsIgnoreCase("POST"))
    {
        PostMethod post = new PostMethod(url.toString());
        httpMethod = post;
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(req.getBody(), req.getType());
        if (req.getBody().length > DEFAULT_SAVEPOST_BUFFER)
        {
            post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        }
        post.setRequestEntity(requestEntity);
        // Note: not able to automatically follow redirects for POST, this is handled by sendRemoteRequest
    }
    else if(method.equalsIgnoreCase("HEAD"))
    {
        HeadMethod head = new HeadMethod(url.toString());
        httpMethod = head;
        httpMethod.setFollowRedirects(true);
    }
    else
    {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }

    if (req.getHeaders() != null)
    {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet())
        {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }
    
    return httpMethod;
}
 
Example #14
Source File: HostObjectUtils.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public static NativeObject sendHttpHEADRequest(String urlVal, String invalidStatusCodesRegex) {
    boolean isConnectionError = true;
    String response = null;
    NativeObject data = new NativeObject();
    //HttpClient client = new DefaultHttpClient();
    HttpHead head = new HttpHead(urlVal);
    //Change implementation to use http client as default http client do not work properly with mutual SSL.
    org.apache.commons.httpclient.HttpClient clientnew = new org.apache.commons.httpclient.HttpClient();
    // extract the host name and add the Host http header for sanity
    head.addHeader("Host", urlVal.replaceAll("https?://", "").replaceAll("(/.*)?", ""));
    clientnew.getParams().setParameter("http.socket.timeout", 4000);
    clientnew.getParams().setParameter("http.connection.timeout", 4000);
    HttpMethod method = new HeadMethod(urlVal);

    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);
        clientnew.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(proxyHost, Integer.parseInt(proxyPort)));
    }

    try {
        int statusCodeNew = clientnew.executeMethod(method);
        //Previous implementation
        // HttpResponse httpResponse = client.execute(head);
        String statusCode = String.valueOf(statusCodeNew);//String.valueOf(httpResponse.getStatusLine().getStatusCode());
        String reasonPhrase = String.valueOf(statusCodeNew);//String.valueOf(httpResponse.getStatusLine().getReasonPhrase());
        //If the endpoint doesn't match the regex which specify the invalid status code, it will return success.
        if (!statusCode.matches(invalidStatusCodesRegex)) {
            if (log.isDebugEnabled() && statusCode.equals(String.valueOf(HttpStatus.SC_METHOD_NOT_ALLOWED))) {
                log.debug("Endpoint doesn't support HTTP HEAD");
            }
            response = "success";
            isConnectionError = false;

        } else {
            //This forms the real backend response to be sent to the client
            data.put("statusCode", data, statusCode);
            data.put("reasonPhrase", data, reasonPhrase);
            response = "";
            isConnectionError = false;
        }
    } catch (IOException e) {
        // sending a default error message.
        log.error("Error occurred while connecting to backend : " + urlVal + ", reason : " + e.getMessage(), e);
        String[] errorMsg = e.getMessage().split(": ");
        if (errorMsg.length > 1) {
            response = errorMsg[errorMsg.length - 1]; //This is to get final readable part of the error message in the exception and send to the client
            isConnectionError = false;
        }
    } finally {
        method.releaseConnection();
    }
    data.put("response", data, response);
    data.put("isConnectionError", data, isConnectionError);
    return data;
}
 
Example #15
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Override
protected final HeadMethod doCreateMethod(String uri) {
  return new HeadMethod(uri);
}
 
Example #16
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Override
protected final HeadMethod doCreateMethod(String uri) {
  return new HeadMethod(uri);
}
 
Example #17
Source File: SwiftRestClient.java    From sahara-extra with Apache License 2.0 4 votes vote down vote up
@Override
protected final HeadMethod doCreateMethod(String uri) {
  return new HeadMethod(uri);
}
 
Example #18
Source File: HeadResponseHandler.java    From development with Apache License 2.0 2 votes vote down vote up
/**
 * Default constructor, will only call the super-constructor
 * for BasicResponseHandler. 
 * 
 * @param method The method used for this response
 */
public HeadResponseHandler(HeadMethod method) {
    super(method);
}