Example usage for org.apache.commons.httpclient HttpMethod setRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethod setRequestHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setRequestHeader.

Prototype

public abstract void setRequestHeader(String paramString1, String paramString2);

Source Link

Usage

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private void setHeaders(HttpMethod method, Map<String, String> headers) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        method.setRequestHeader(entry.getKey(), entry.getValue());
    }/*from w w w .j  ava2 s.  co m*/
}

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

@Override
public boolean handleMailboxChange(String accountId) {
    String email = getEmailAddress(accountId);
    ServerInfo serverInfo = getServerInfo(email);
    if (email == null || !serverInfo.enabled) {
        return true; // no retry
    }/*from  w w  w  . ja  va2s. co  m*/
    FreeBusy fb;
    try {
        fb = getFreeBusy(accountId, FreeBusyQuery.CALENDAR_FOLDER_ALL);
    } catch (ServiceException se) {
        ZimbraLog.fb.warn("can't get freebusy for account " + accountId, se);
        // retry the request if it's receivers fault.
        return !se.isReceiversFault();
    }
    if (email == null || fb == null) {
        ZimbraLog.fb.warn("account not found / incorrect / wrong host: " + accountId);
        return true; // no retry
    }
    if (serverInfo == null || serverInfo.org == null || serverInfo.cn == null) {
        ZimbraLog.fb.warn("no exchange server info for user " + email);
        return true; // no retry
    }
    ExchangeMessage msg = new ExchangeMessage(serverInfo.org, serverInfo.cn, email);
    String url = serverInfo.url + msg.getUrl();

    HttpMethod method = null;

    try {
        ZimbraLog.fb.debug("POST " + url);
        method = msg.createMethod(url, fb);
        method.setRequestHeader(HEADER_TRANSLATE, "f");
        int status = sendRequest(method, serverInfo);
        if (status != MULTI_STATUS) {
            InputStream resp = method.getResponseBodyAsStream();
            String respStr = (resp == null ? "" : new String(ByteUtil.readInput(resp, 1024, 1024), "UTF-8"));
            ZimbraLog.fb.error("cannot modify resource at %s : http error %d, buf (%s)", url, status, respStr);
            return false; // retry
        }
    } catch (IOException ioe) {
        ZimbraLog.fb.error("error communicating with " + serverInfo.url, ioe);
        return false; // retry
    } finally {
        method.releaseConnection();
    }
    return true;
}

From source file:com.owncloud.android.oc_framework.network.webdav.WebdavClient.java

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    boolean customRedirectionNeeded = false;
    try {/* ww  w. ja  v a 2s .c o m*/
        method.setFollowRedirects(mFollowRedirects);
    } catch (Exception e) {
        //if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed");
        customRedirectionNeeded = mFollowRedirects;
    }
    if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
        method.setRequestHeader("Cookie", mSsoSessionCookie);
    }
    int status = super.executeMethod(method);
    int redirectionsCount = 0;
    while (customRedirectionNeeded && redirectionsCount < MAX_REDIRECTIONS_COUNT
            && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY
                    || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location != null) {
            Log.d(TAG, "Location to redirect: " + location.getValue());
            method.setURI(new URI(location.getValue(), true));
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log.d(TAG, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }

    return status;
}

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

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    boolean customRedirectionNeeded = false;
    try {/* w w w .j a  va 2 s  . c om*/
        method.setFollowRedirects(mFollowRedirects);
    } catch (Exception e) {
        if (mFollowRedirects)
            Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName()
                    + " method, custom redirection will be used");
        customRedirectionNeeded = mFollowRedirects;
    }
    if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
        method.setRequestHeader("Cookie", mSsoSessionCookie);
    }
    int status = super.executeMethod(method);
    int redirectionsCount = 0;
    while (customRedirectionNeeded && redirectionsCount < MAX_REDIRECTIONS_COUNT
            && (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY
                    || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location != null) {
            Log_OC.d(TAG, "Location to redirect: " + location.getValue());
            method.setURI(new URI(location.getValue(), true));
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }

    return status;
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to send a GET request to the path passed using the http client
 *
 * @param path the path on which the request should be sent
 *///ww w.  j av a2 s.c o m
public void sendGetRequest(final String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/"))
        fullpath = baseUrl + path;
    log.info("Sending GET request to " + fullpath);

    final HttpMethod method = new GetMethod(fullpath);
    try {
        for (final Map.Entry<String, String> header : requestHeaders.entrySet())
            method.setRequestHeader(header.getKey(), header.getValue());
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Gets the result of the execution of a get request. the attempt will be
 * repeated several times in case of failures
 *
 * @param path the path on which the request should be sent
 * @throws Exception if something's going wrong...
 *//*from   w w w  .  ja  va  2  s  . c o  m*/
public void retryGetRequestUntilSucceed(@NonNull String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/"))
        fullpath = baseUrl + path;

    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
        for (final Map.Entry<String, String> header : requestHeaders.entrySet())
            method.setRequestHeader(header.getKey(), header.getValue());

        String responseAsString = null;
        int statusCode;
        int attempts = 0;
        boolean success = false;
        do {
            // waiting timeToWait seconds
            Thread.sleep(timeToWait * 1000);
            statusCode = httpClient.executeMethod(method);
            attempts++;
            // check for status code 200
            if (statusCode == HttpStatus.SC_OK) {
                responseAsString = method.getResponseBodyAsString();
                success = true;
                log.info("The result is available! ");
            } else
                log.warn("unsuccessful GET request : " + method.getStatusLine() + " | Waiting " + timeToWait
                        + " seconds ...");
        } while (!success && maxAttempts > attempts);
        response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Gets the result of the execution of a get request. the attempt will be
 * repeated until obtain the exepected result
 *
 * @param path       the path on which the request should be executed
 * @param expression the result that should be returned by the GET request, which
 *                   allows to know if that request is completely processed or not
 * @throws Exception if something's going wrong...
 *//*from   w w w . ja  va  2  s .c  om*/
public void retryGetRequestUntilObtainExpectedResponse(@NonNull String path, @NonNull String expression)
        throws Exception {
    String fullpath = path;
    if (path.startsWith("/"))
        fullpath = baseUrl + path;
    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
        for (final Map.Entry<String, String> header : requestHeaders.entrySet())
            method.setRequestHeader(header.getKey(), header.getValue());

        String responseAsString = null;
        String toCheck = null;
        String expected = expression;
        String prop = null;
        final int idx = expression.indexOf("=");
        if (idx > 0) {
            prop = expression.substring(0, idx);
            expected = expression.substring(idx + 1);
        }
        int statusCode;
        int attempts = 0;
        boolean success = false;
        do {
            // waiting timeToWait seconds
            Thread.sleep(timeToWait * 1000);
            statusCode = httpClient.executeMethod(method);
            attempts++;
            if (statusCode == HttpStatus.SC_OK) {
                responseAsString = method.getResponseBodyAsString();
                toCheck = responseAsString;
                if (prop != null)
                    toCheck = JSONHelper.getPropertyValue(responseAsString, prop);
                if (toCheck.contains(expected)) {
                    success = true;
                    log.debug("The result is available! ");
                } else
                    log.warn("The result is not yet available! | Waiting " + timeToWait + " seconds ...");
            } else
                log.warn("unsuccessful GET request : " + method.getStatusLine() + " | Waiting " + timeToWait
                        + " seconds ...");
        } while (!success && maxAttempts > attempts);
        response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.datos.vfs.provider.webdav.WebdavFileObject.java

/**
 * Prepares a Method object.//from w  w  w.  j  ava 2  s  .  c  o  m
 *
 * @param method the HttpMethod.
 * @throws FileSystemException if an error occurs encoding the uri.
 * @throws URIException        if the URI is in error.
 */
@Override
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
    method.addRequestHeader("Cache-control", "no-cache");
    method.addRequestHeader("Cache-store", "no-store");
    method.addRequestHeader("Pragma", "no-cache");
    method.addRequestHeader("Expires", "0");
}

From source file:de.mpg.escidoc.pubman.viewItem.bean.FileBean.java

/**
 * Adds a cookie named "escidocCookie" that holds the eScidoc user handle to the provided http method object.
 * @author Tobias Schraut//from   w w  w.  j av  a  2 s .  c  o  m
 * @param method The http method to add the cookie to.
 */
private void addHandleToMethod(final HttpMethod method, String eSciDocUserHandle) {
    // Staging file resource is protected, access needs authentication and
    // authorization. Therefore, the eSciDoc user handle must be provided.
    // Put the handle in the cookie "escidocCookie"
    method.setRequestHeader("Cookie", "escidocCookie=" + eSciDocUserHandle);
}

From source file:JiraWebClient.java

private void prepareSecurityToken(HttpMethod method) {
    // this one is required as of JIRA 4.1
    // see http://confluence.atlassian.com/display/JIRA/Form+Token+Handling#FormTokenHandling-Scripting
    method.setRequestHeader("X-Atlassian-Token", "no-check"); //$NON-NLS-1$//$NON-NLS-2$
}