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:com.owncloud.android.oc_framework.network.webdav.WebdavClient.java

/**
 * Check if a file exists in the OC server
 * //  w  w  w  .  ja v a2s.c o  m
 * TODO replace with ExistenceOperation
 * 
 * @return              'true' if the file exists; 'false' it doesn't exist
 * @throws  Exception   When the existence could not be determined
 */
public boolean existsFile(String path) throws IOException, HttpException {
    HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
    try {
        int status = executeMethod(head);
        Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status
                + ((status != HttpStatus.SC_OK) ? "(FAIL)" : ""));
        exhaustResponse(head.getResponseBodyAsStream());
        return (status == HttpStatus.SC_OK);

    } finally {
        head.releaseConnection(); // let the connection available for other methods
    }
}

From source file:jails.http.client.CommonsClientHttpRequestFactory.java

/**
 * Create a Commons HttpMethodBase object for the given HTTP method
 * and URI specification.//  ww  w. j  a  v  a 2 s . c  o  m
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) {
    switch (httpMethod) {
    case GET:
        return new GetMethod(uri);
    case DELETE:
        return new DeleteMethod(uri);
    case HEAD:
        return new HeadMethod(uri);
    case OPTIONS:
        return new OptionsMethod(uri);
    case POST:
        return new PostMethod(uri);
    case PUT:
        return new PutMethod(uri);
    case TRACE:
        return new TraceMethod(uri);
    default:
        throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}

From source file:com.sittinglittleduck.DirBuster.workGenerators.WorkerGeneratorURLFuzz.java

/** Thread run method */
public void run() {

    /*//w  w w. ja  v a  2  s . co  m
     * Read in all the items and create all the work we need to.
     */

    BufferedReader d = null;
    try {
        manager.setURLFuzzGenFinished(false);
        String currentDir = "/";
        int failcode = 404;
        String line;
        Vector extToCheck = new Vector(10, 5);
        boolean recursive = true;
        int passTotal = 0;

        try {
            d = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
            passTotal = 0;
            while ((line = d.readLine()) != null) {
                if (!line.startsWith("#")) {
                    passTotal++;
                }
            }
            manager.setTotalPass(passTotal);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        if (manager.getAuto()) {
            try {
                URL headurl = new URL(firstPart);
                HeadMethod httphead = new HeadMethod(headurl.toString());
                Vector HTTPheaders = manager.getHTTPHeaders();
                for (int a = 0; a < HTTPheaders.size(); a++) {
                    HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
                    httphead.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
                }
                httphead.setFollowRedirects(Config.followRedirects);
                int responceCode = httpclient.executeMethod(httphead);
                if (Config.debug) {
                    System.out.println("DEBUG WokerGen: responce code for head check = " + responceCode);
                }
                if (responceCode == 501 || responceCode == 400 || responceCode == 405) {
                    if (Config.debug) {
                        System.out.println(
                                "DEBUG WokerGen: Changing to GET only HEAD test returned 501(method no implmented) or a 400");
                    }
                    manager.setAuto(false);
                }
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            }
        }

        d = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
        System.out.println("Starting fuzz on " + firstPart + urlFuzzStart + "{dir}" + urlFuzzEnd);
        int filesProcessed = 0;

        BaseCase baseCaseObj = GenBaseCase.genURLFuzzBaseCase(manager, firstPart + urlFuzzStart, urlFuzzEnd);

        while ((line = d.readLine()) != null) {
            if (stopMe) {
                return;
            }

            if (!line.startsWith("#")) {
                String method;
                if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode()
                        && !baseCaseObj.isUseRegexInstead()) {
                    method = "HEAD";
                } else {
                    method = "GET";
                }

                // url encode all the items
                line = URLEncoder.encode(line);

                URL currentURL = new URL(firstPart + urlFuzzStart + line + urlFuzzEnd);
                // BaseCase baseCaseObj = new BaseCase(currentURL, failcode, true, failurl,
                // baseResponce);
                // if the base case is null then we need to switch to content anylsis mode
                workQueue.put(new WorkUnit(currentURL, true, method, baseCaseObj, line));
            }

            Thread.sleep(3);
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(WorkerGeneratorURLFuzz.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(WorkerGeneratorURLFuzz.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(WorkerGeneratorURLFuzz.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            d.close();
            manager.setURLFuzzGenFinished(true);
        } catch (IOException ex) {
            Logger.getLogger(WorkerGeneratorURLFuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.sittinglittleduck.DirBuster.workGenerators.WorkerGenerator.java

/** Thread run method */
public void run() {
    String currentDir = "/";
    int failcode = 404;
    String line;//from  w w w.  j av  a2  s. co  m
    Vector extToCheck = new Vector(10, 5);
    boolean recursive = true;
    int passTotal = 0;

    // --------------------------------------------------
    try {

        // find the total number of requests to be made, per pass
        // based on the fact there is a single entry per line
        BufferedReader d = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
        passTotal = 0;
        while ((line = d.readLine()) != null) {
            if (!line.startsWith("#")) {
                passTotal++;
            }
        }

        manager.setTotalPass(passTotal);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    // -------------------------------------------------

    // checks if the server surports heads requests
    if (manager.getAuto()) {
        try {
            URL headurl = new URL(firstPart);

            HeadMethod httphead = new HeadMethod(headurl.toString());

            // set the custom HTTP headers
            Vector HTTPheaders = manager.getHTTPHeaders();
            for (int a = 0; a < HTTPheaders.size(); a++) {
                HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
                /*
                 * Host header has to be set in a different way!
                 */
                if (httpHeader.getHeader().startsWith("Host:")) {
                    httphead.getParams().setVirtualHost(httpHeader.getValue());
                } else {
                    httphead.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
                }
            }

            httphead.setFollowRedirects(Config.followRedirects);
            int responceCode = httpclient.executeMethod(httphead);

            if (Config.debug) {
                System.out.println("DEBUG WokerGen: responce code for head check = " + responceCode);
            }

            // if the responce code is method not implemented or if the head requests return
            // 400!
            if (responceCode == 501 || responceCode == 400 || responceCode == 405) {
                if (Config.debug) {
                    System.out.println(
                            "DEBUG WokerGen: Changing to GET only HEAD test returned 501(method no implmented) or a 400");
                }
                // switch the mode to just GET requests
                manager.setAuto(false);
            }
        } catch (MalformedURLException e) {
            // TODO deal with error
        } catch (IOException e) {
            // TODO deal with error
        }
    }

    // end of checks to see if server surpports head requests
    int counter = 0;

    while ((!dirQueue.isEmpty() || !workQueue.isEmpty() || !manager.areWorkersAlive()) && recursive) {
        // get the dir we are about to process
        String baseResponce = null;
        recursive = manager.isRecursive();
        BaseCase baseCaseObj = null;

        // rest the skip
        skipCurrent = false;

        // deal with the dirs
        try {
            // get item from  queue
            // System.out.println("gen about to take");
            DirToCheck tempDirToCheck = dirQueue.take();
            // System.out.println("gen taken");
            // get dir name
            currentDir = tempDirToCheck.getName();
            // get any extention that need to be checked
            extToCheck = tempDirToCheck.getExts();

            manager.setCurrentlyProcessing(currentDir);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        started = currentDir;

        // generate the list of dirs
        if (manager.getDoDirs()) {
            // find the fail case for the dir
            URL failurl = null;

            try {
                baseResponce = null;

                baseCaseObj = GenBaseCase.genBaseCase(manager, firstPart + currentDir, true, null);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // end of dir fail case
            if (stopMe) {
                return;
            }

            // generate work links
            try {
                // readin dir names
                BufferedReader d = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));

                if (Config.debug) {
                    System.out.println("DEBUG WokerGen: Generating dir list for " + firstPart);
                }

                URL currentURL;

                // add the first item while doing dir's
                if (counter == 0) {
                    try {
                        String method;
                        if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode()
                                && !baseCaseObj.isUseRegexInstead()) {
                            method = "HEAD";
                        } else {
                            method = "GET";
                        }
                        currentURL = new URL(firstPart + currentDir);
                        // System.out.println("first part = " + firstPart);
                        // System.out.println("current dir = " + currentDir);
                        workQueue.put(new WorkUnit(currentURL, true, "GET", baseCaseObj, null));
                        if (Config.debug) {
                            System.out.println("DEBUG WokerGen: 1 adding dir to work list " + method + " "
                                    + currentDir.toString());
                        }
                    } catch (MalformedURLException ex) {
                        ex.printStackTrace();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                } // end of dealing with first item
                int dirsProcessed = 0;

                // add the rest of the dirs
                while ((line = d.readLine()) != null) {
                    // code to skip the current work load
                    if (skipCurrent) {
                        // add the totalnumber per pass - the amount process this pass to the
                        // work correction total
                        manager.addToWorkCorrection(passTotal - dirsProcessed);
                        break;
                    }

                    // if the line is not empty or starts with a #
                    if (!line.equalsIgnoreCase("") && !line.startsWith("#")) {
                        line = line.trim();
                        line = makeItemsafe(line);
                        try {
                            String method;
                            if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode()
                                    && !baseCaseObj.isUseRegexInstead()) {
                                method = "HEAD";
                            } else {
                                method = "GET";
                            }

                            currentURL = new URL(firstPart + currentDir + line + "/");
                            // BaseCase baseCaseObj = new BaseCase(currentURL, failcode, true,
                            // failurl, baseResponce);
                            // if the base case is null then we need to switch to content
                            // anylsis mode

                            // System.out.println("Gen about to add to queue");
                            workQueue.put(new WorkUnit(currentURL, true, method, baseCaseObj, line));
                            // System.out.println("Gen finshed adding to queue");
                            if (Config.debug) {
                                System.out.println("DEBUG WokerGen: 2 adding dir to work list " + method + " "
                                        + currentURL.toString());
                            }
                        } catch (MalformedURLException e) {
                            // TODO deal with bad line
                            // e.printStackTrace();
                            // do nothing if it's malformed, I dont care about them!
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        // if there is a call to stop the work gen then stop!
                        if (stopMe) {
                            return;
                        }
                        dirsProcessed++;
                    }
                } // end of while
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // generate the list of files
        if (manager.getDoFiles()) {

            baseResponce = null;
            URL failurl = null;

            // loop for all the different file extentions
            for (int b = 0; b < extToCheck.size(); b++) {
                // only test if we are surposed to
                ExtToCheck extTemp = (ExtToCheck) extToCheck.elementAt(b);

                if (extTemp.toCheck()) {

                    fileExtention = "";
                    if (extTemp.getName().equals(ExtToCheck.BLANK_EXT)) {
                        fileExtention = "";
                    } else {
                        fileExtention = "." + extTemp.getName();
                    }

                    try {
                        // get the base for this extention
                        baseCaseObj = GenBaseCase.genBaseCase(manager, firstPart + currentDir, false,
                                fileExtention);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    // if the manager has sent the stop command then exit
                    if (stopMe) {
                        return;
                    }

                    try {
                        BufferedReader d = new BufferedReader(
                                new InputStreamReader(new FileInputStream(inputFile)));
                        // if(failcode != 200)
                        // {
                        int filesProcessed = 0;

                        while ((line = d.readLine()) != null) {
                            // code to skip the current work load
                            if (skipCurrent) {
                                manager.addToWorkCorrection(passTotal - filesProcessed);
                                break;
                            }
                            // dont process is the line empty for starts with a #
                            if (!line.equalsIgnoreCase("") && !line.startsWith("#")) {
                                line = line.trim();
                                line = makeItemsafe(line);
                                try {
                                    String method;
                                    if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode()
                                            && !baseCaseObj.isUseRegexInstead()) {
                                        method = "HEAD";
                                    } else {
                                        method = "GET";
                                    }

                                    URL currentURL = new URL(firstPart + currentDir + line + fileExtention);
                                    // BaseCase baseCaseObj = new BaseCase(currentURL, true,
                                    // failurl, baseResponce);
                                    workQueue.put(new WorkUnit(currentURL, false, method, baseCaseObj, line));
                                    if (Config.debug) {
                                        System.out.println("DEBUG WokerGen: adding file to work list " + method
                                                + " " + currentURL.toString());
                                    }
                                } catch (MalformedURLException e) {
                                    // e.printStackTrace();
                                    // again do nothing as I dont care
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                if (stopMe) {
                                    return;
                                }
                                filesProcessed++;
                            }
                        } // end of while
                          // }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } // end of file ext loop
        } // end of if files
        finished = started;

        counter++;
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    } // end of main while
      // System.out.println("Gen FINISHED!");
      // manager.youAreFinished();
}

From source file:eu.alefzero.webdav.WebdavClient.java

/**
 * Check if a file exists in the OC server
 * /*  w  w w.  ja va 2  s .  c  o m*/
 * TODO replace with ExistenceOperation
 * 
 * @return              'true' if the file exists; 'false' it doesn't exist
 * @throws  Exception   When the existence could not be determined
 */
public boolean existsFile(String path) throws IOException, HttpException {
    HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
    try {
        int status = executeMethod(head);
        Log_OC.d(TAG, "HEAD to " + path + " finished with HTTP status " + status
                + ((status != HttpStatus.SC_OK) ? "(FAIL)" : ""));
        exhaustResponse(head.getResponseBodyAsStream());
        return (status == HttpStatus.SC_OK);

    } finally {
        head.releaseConnection(); // let the connection available for other methods
    }
}

From source file:liveplugin.toolwindow.addplugin.git.jetbrains.plugins.github.api.GithubApiUtil.java

@NotNull
private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri,
        @Nullable final String requestBody, @NotNull final Collection<Header> headers,
        @NotNull final HttpVerb verb) throws IOException {
    HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy());
    return GithubSslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
            new ThrowableConvertor<String, HttpMethod, IOException>() {
                @Override/*w  ww.jav a2 s  .  co m*/
                public HttpMethod convert(String uri) throws IOException {
                    HttpMethod method;
                    switch (verb) {
                    case POST:
                        method = new PostMethod(uri);
                        if (requestBody != null) {
                            ((PostMethod) method).setRequestEntity(
                                    new StringRequestEntity(requestBody, "application/json", "UTF-8"));
                        }
                        break;
                    case GET:
                        method = new GetMethod(uri);
                        break;
                    case DELETE:
                        method = new DeleteMethod(uri);
                        break;
                    case HEAD:
                        method = new HeadMethod(uri);
                        break;
                    default:
                        throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString());
                    }
                    GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
                    if (tokenAuth != null) {
                        method.addRequestHeader("Authorization", "token " + tokenAuth.getToken());
                    }
                    for (Header header : headers) {
                        method.addRequestHeader(header);
                    }
                    return method;
                }
            });
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Setup the request./*  w  w  w  . jav a 2s . c o  m*/
 *
 * @param context the context
 */
protected void setupRequest(ProxyContext context) {
    // set the proxy to send requests through
    ExternalProxySettings externalProxy = context.getExternalProxySettings();
    if (externalProxy != null) {
        String proxyServer = externalProxy.getProxyServer();

        if (proxyServer != null) {
            context.getTarget().getHostConfig().setProxy(proxyServer, externalProxy.getProxyPort());
            if (context.getProxyCredentials() != null) {
                context.getHttpClient().getState().setProxyCredentials(ProxyUtil.getDefaultAuthScope(),
                        context.getProxyCredentials());
            }
        }
    }

    String method = context.getMethod();
    String encodedPath = context.getTarget().getEncodedPath();
    if (MessageIOConstants.METHOD_POST.equals(method)) {
        FlexPostMethod postMethod = new FlexPostMethod(encodedPath);
        context.setHttpMethod(postMethod);
        if (context.hasAuthorization()) {
            postMethod.setConnectionForced(true);
        }
    } else if (ProxyConstants.METHOD_GET.equals(method)) {
        FlexGetMethod getMethod = new FlexGetMethod(context.getTarget().getEncodedPath());
        context.setHttpMethod(getMethod);
        if (context.hasAuthorization()) {
            getMethod.setConnectionForced(true);
        }
    } else if (ProxyConstants.METHOD_HEAD.equals(method)) {
        HeadMethod headMethod = new HeadMethod(encodedPath);
        context.setHttpMethod(headMethod);
    } else if (ProxyConstants.METHOD_PUT.equals(method)) {
        PutMethod putMethod = new PutMethod(encodedPath);
        context.setHttpMethod(putMethod);
    } else if (ProxyConstants.METHOD_OPTIONS.equals(method)) {
        OptionsMethod optionsMethod = new OptionsMethod(encodedPath);
        context.setHttpMethod(optionsMethod);
    } else if (ProxyConstants.METHOD_DELETE.equals(method)) {
        DeleteMethod deleteMethod = new DeleteMethod(encodedPath);
        context.setHttpMethod(deleteMethod);
    } else if (ProxyConstants.METHOD_TRACE.equals(method)) {
        TraceMethod traceMethod = new TraceMethod(encodedPath);
        context.setHttpMethod(traceMethod);
    } else {
        ProxyException pe = new ProxyException(INVALID_METHOD);
        pe.setDetails(INVALID_METHOD, "1", new Object[] { method });
        throw pe;
    }

    HttpMethodBase httpMethod = context.getHttpMethod();
    if (httpMethod instanceof EntityEnclosingMethod) {
        ((EntityEnclosingMethod) httpMethod).setContentChunked(context.getContentChunked());
    }
}

From source file:com.foglyn.fogbugz.Request.java

/**
 * Returns headers returned by server for given URL. We use HEAD request. Keys in result map are lower case.
 *///from w w  w  .  jav  a2s . com
Map<String, String> getHeaders(String url, IProgressMonitor monitor) throws FogBugzException {
    HeadMethod method = new HeadMethod(url);

    return request(url, method, monitor, new HeadersResponseProcessor());
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri,
        @Nullable final String requestBody, @NotNull final Collection<Header> headers,
        @NotNull final HttpVerb verb) throws IOException {
    HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy());
    HttpMethod method;//from   ww w.  j  a v a  2 s  .c  o  m
    switch (verb) {
    case POST:
        method = new PostMethod(uri);
        if (requestBody != null) {
            ((PostMethod) method)
                    .setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8"));
        }
        break;
    case GET:
        method = new GetMethod(uri);
        break;
    case DELETE:
        method = new DeleteMethod(uri);
        break;
    case HEAD:
        method = new HeadMethod(uri);
        break;
    default:
        throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString());
    }
    GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
    if (tokenAuth != null) {
        method.addRequestHeader("Authorization", "token " + tokenAuth.getToken());
    }
    for (Header header : headers) {
        method.addRequestHeader(header);
    }

    client.executeMethod(method);
    return method;
}

From source file:com.thoughtworks.go.agent.launcher.ServerBinaryDownloader.java

Map<String, String> headers() throws Exception {
    Map<String, String> headers = ServerCall.invoke(new HeadMethod(checkUrl())).headers;
    checkHeaders(headers, downloadableFile.url(urlGenerator));
    return headers;
}