Example usage for org.apache.commons.httpclient HttpMethodBase addRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethodBase addRequestHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase addRequestHeader.

Prototype

@Override
public void addRequestHeader(String headerName, String headerValue) 

Source Link

Document

Adds the specified request header, NOT overwriting any previous value.

Usage

From source file:com.eucalyptus.blockstorage.HttpTransfer.java

/**
 * Calculates the canonical and signed header strings in a single pass, done in one pass for efficiency
 * @param httpBaseRequest//from  w ww  . j av a 2s  .  c  o  m
 * @return Array of 2 elements, first element is the canonicalHeader string, second element is the signedHeaders string
 */
private static String[] getCanonicalAndSignedHeaders(HttpMethodBase httpBaseRequest) {
    /*
     * The host header is required for EucaV2 signing, but it is not constructed by the HttpClient until the method is executed.
     * So, here we add a header with the same value and name so that we can do the proper sigining, but know that this value will
     * be overwritten when HttpMethodBase is executed to send the request.
     * 
     * This code is specific to the jakarta commons httpclient because that client will set the host header to hostname:port rather than
     * just hostname.
     * 
     * Supposedly you can force the value of the Host header with: httpBaseRequest.getParams().setVirtualHost("hostname"), but that was not successful
     */
    try {
        httpBaseRequest.addRequestHeader("Host",
                httpBaseRequest.getURI().getHost() + ":" + httpBaseRequest.getURI().getPort());
    } catch (URIException e) {
        LOG.error(
                "Could not add Host header for canonical headers during authorization header creation in HTTP client: ",
                e);
        return null;
    }

    Header[] headers = httpBaseRequest.getRequestHeaders();
    StringBuilder signedHeaders = new StringBuilder();
    StringBuilder canonicalHeaders = new StringBuilder();

    if (headers != null) {
        Arrays.sort(headers, new Comparator<Header>() {
            @Override
            public int compare(Header arg0, Header arg1) {
                return arg0.getName().toLowerCase().compareTo(arg1.getName().toLowerCase());
            }

        });

        for (Header header : headers) {
            //Add to the signed headers
            signedHeaders.append(header.getName().toLowerCase()).append(';');
            //Add the name and value to the canonical header
            canonicalHeaders.append(header.getName().toLowerCase()).append(':').append(header.getValue().trim())
                    .append('\n');
        }

        if (signedHeaders.length() > 0) {
            signedHeaders.deleteCharAt(signedHeaders.length() - 1); //Delete the trailing semi-colon
        }

        if (canonicalHeaders.length() > 0) {
            canonicalHeaders.deleteCharAt(canonicalHeaders.length() - 1); //Delete the trialing '\n' just to make things clear and consistent
        }
    }
    String[] result = new String[2];
    result[0] = canonicalHeaders.toString();
    result[1] = signedHeaders.toString();
    return result;
}

From source file:com.tasktop.c2c.server.auth.service.proxy.ProxyPreAuthHttpRequestFactory.java

@Override
public void postProcessCommonsHttpMethod(final HttpMethodBase httpMethod) {
    final AuthenticationToken authenticationToken = ProxyClient.getAuthenticationToken();
    if (authenticationToken != null) {
        tokenSerializer.serialize(new RequestHeaders() {
            @Override//from  w  ww .j a  va2  s.co m
            public void addHeader(String name, String value) {
                httpMethod.addRequestHeader(name, value);
            }
        }, authenticationToken);
    }

    // Also setup the tenancy context headers
    for (Entry<String, String> header : tenancySerializer.computeHeaders().entrySet()) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
}

From source file:com.kylinolap.jdbc.stub.KylinClient.java

private void addPostHeaders(HttpMethodBase method) {
    method.addRequestHeader("Accept", "application/json, text/plain, */*");
    method.addRequestHeader("Content-Type", "application/json");
    method.addRequestHeader("Authorization", "Basic " + conn.getBasicAuthHeader());
}

From source file:net.sf.sail.webapp.domain.webservice.http.impl.HttpRestTransportImpl.java

private void setHeaders(final AbstractHttpRequest httpRequestData, HttpMethodBase method) {
    final Map<String, String> requestHeaders = httpRequestData.getRequestHeaders();
    if (requestHeaders != null && !requestHeaders.isEmpty()) {
        Set<String> keys = requestHeaders.keySet();
        for (String key : keys) {
            method.addRequestHeader(key, requestHeaders.get(key));
        }// w w w.  j  a  v a2 s  . c o m
    }
}

From source file:com.esri.gpt.control.webharvest.client.ckan.CkanIterator.java

protected HttpClientRequest newClientRequest(final Bots bots) {
    if (bots != null) {
        return new HttpCrawlRequest(bots) {
            @Override//from  w  w  w  .  java 2  s  . co  m
            protected HttpMethodBase createMethod() throws IOException {
                HttpMethodBase method = super.createMethod();
                String userAgent = Val.chkStr(!Val.chkStr(bots.getUserAgent()).isEmpty() ? bots.getUserAgent()
                        : config.getDefaultUserAgent());
                if (!userAgent.isEmpty()) {
                    method.addRequestHeader("User-Agent", userAgent);
                }
                return method;
            }
        };
    } else {
        return new HttpClientRequest() {
            @Override
            protected HttpMethodBase createMethod() throws IOException {
                HttpMethodBase method = super.createMethod();
                String userAgent = Val.chkStr(config.getDefaultUserAgent());
                if (!userAgent.isEmpty()) {
                    method.addRequestHeader("User-Agent", userAgent);
                }
                return method;
            }
        };
    }
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int logout() {
    log.finest("Logout");
    try {//from   ww  w . ja v  a 2s  .  c  om
        log.finest("URI:" + url.toURI().toString());
    } catch (URISyntaxException ex) {
        log.finest("Logout URISyntaxException " + ex.getMessage());
    }

    String logoutUrl = this.url.toString() + contextRoot + JAZZ_LOGOUT_URL;
    log.finest("Attempting to log out with this url: " + logoutUrl);
    HttpMethodBase authenticationMethod = new PostMethod(this.url.toString() + contextRoot + JAZZ_LOGOUT_URL);
    authenticationMethod.setFollowRedirects(false);
    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) super.getState()
            .getCredentials(new AuthScope(host, port));
    if (null != credentials && !(credentials.getUserName().isEmpty() && credentials.getPassword().isEmpty())) {

        log.finest(String.format("Adding authorizationheadder for logout for user: %s",
                credentials.getUserName()));
        authenticationMethod.addRequestHeader("Authorization:",
                "Base " + credentials.getUserName() + ":" + credentials.getPassword());
    }
    String body = "";
    String status = "";
    int responseCode = 0;
    ;
    try {
        responseCode = executeMethod(authenticationMethod);
        body = authenticationMethod.getResponseBodyAsString();
        status = authenticationMethod.getStatusText();
        log.finest(String.format("Response code %s, Status text %s", responseCode, status));
    } catch (Exception e) {
        log.log(Level.SEVERE, "Failed to log out!", e);
        log.log(Level.SEVERE, body);
    }
    return responseCode;
}

From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java

private void overrideHeaders(HttpMethodBase httpMethod, String url, String method) {
    String headers = getRequestHeaders();
    String[] header = headers.split(System.getProperty("line.separator"));
    for (String kvp : header) {
        int pos = kvp.indexOf(':');
        if (pos < 0)
            pos = kvp.indexOf('=');
        if (pos > 0) {
            String k = kvp.substring(0, pos).trim();
            String v = "";
            if (kvp.length() > pos + 1)
                v = kvp.substring(pos + 1).trim();
            httpMethod.addRequestHeader(k, v);
        }//from   www  .  j a  v a 2 s .c o m
    }
    String authorization = OAuthGenerator.getInstance(getConsumerKey(), getConsumerSecret())
            .getAuthorization(url, method);
    httpMethod.addRequestHeader("Authorization", authorization);
}

From source file:com.atlantbh.jmeter.plugins.rest.RestSampler.java

private void overrideHeaders(HttpMethodBase httpMethod) {
    String headers = getRequestHeaders();
    String[] header = headers.split(System.getProperty("line.separator"));
    for (String kvp : header) {
        int pos = kvp.indexOf(':');
        if (pos < 0)
            pos = kvp.indexOf('=');
        if (pos > 0) {
            String k = kvp.substring(0, pos).trim();
            String v = "";
            if (kvp.length() > pos + 1)
                v = kvp.substring(pos + 1).trim();
            httpMethod.addRequestHeader(k, v);
        }/* w w  w  .  j  ava  2  s  .c om*/
    }
}

From source file:jeeves.utils.XmlRequest.java

private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException {
    HttpMethodBase httpMethod;

    if (method == Method.GET) {
        httpMethod = new GetMethod();

        if (query != null && !query.equals(""))
            httpMethod.setQueryString(query);

        else if (alSimpleParams.size() != 0)
            httpMethod.setQueryString(alSimpleParams.toArray(new NameValuePair[alSimpleParams.size()]));

        httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
        httpMethod.setFollowRedirects(true);
    } else {/*from   w  w  w.j av  a 2s  . c  om*/
        PostMethod post = new PostMethod();

        if (!useSOAP) {
            postData = (postParams == null) ? "" : Xml.getString(new Document(postParams));
            post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8"));
        } else {
            postData = Xml.getString(new Document(soapEmbed(postParams)));
            post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8"));
        }

        httpMethod = post;
    }

    httpMethod.setPath(address);
    httpMethod.setDoAuthentication(useAuthent());

    return httpMethod;
}

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

/**
 * @param client Client object//from  ww w.  ja  v  a2 s.co m
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    HttpMethodBase method = null;

    ReadRemoteFolderOperation remoteFolderOperation = new ReadRemoteFolderOperation(remotePath);
    RemoteOperationResult remoteFolderOperationResult = remoteFolderOperation.execute(client);

    // Abort if not empty
    // Result has always the folder and maybe children, so size == 1 is ok
    if (remoteFolderOperationResult.isSuccess() && remoteFolderOperationResult.getData().size() > 1) {
        return new RemoteOperationResult(false, "Non empty", HttpStatus.SC_FORBIDDEN);
    }

    try {
        String url = client.getBaseUri() + ENCRYPTED_URL + localId;
        if (encryption) {
            method = new PutMethod(url);
        } else {
            method = new DeleteMethod(url);
        }

        // remote request
        method.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        method.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);

        int status = client.executeMethod(method, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            result = new RemoteOperationResult(true, method);
        } else {
            result = new RemoteOperationResult(false, method);
            client.exhaustResponse(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Setting encryption status of " + localId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return result;
}