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

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

Introduction

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

Prototype

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

Source Link

Document

Set the specified request header, overwriting any previous value.

Usage

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void copyRequestHeaders(HttpServletRequest request, HttpMethodBase method) {

    Enumeration properties = request.getHeaderNames();
    while (properties.hasMoreElements()) {
        String propertyName = (String) properties.nextElement();
        String propertyNameToLower = propertyName.toLowerCase();
        if (!ignoreRequestHeaders.contains(propertyNameToLower) && !(method instanceof GetMethod
                && ignorePostToGetRequestHeaders.contains(propertyNameToLower))) {
            Enumeration values = request.getHeaders(propertyName);
            while (values.hasMoreElements()) {
                String property = (String) values.nextElement();
                // System.out.println(propertyName + ":" + property);
                method.setRequestHeader(propertyName, property);
            }/*from  www.  j  ava 2s  .c om*/
        }
    }

    // TODO consider what happens if the host is different after a redirect...
    // Conditional cookie transfer
    try {
        org.apache.commons.httpclient.URI uri = method.getURI();
        if (uri != null) {
            String host = uri.getHost();
            if (host != null) {
                if (host.equals(request.getHeader("host"))) {
                    String cookie = request.getHeader("cookie");
                    if (cookie != null)
                        method.setRequestHeader("cookie", cookie);
                }
            } else {
                log.warn("host is null for uri " + uri);
            }
        } else {
            log.warn("uri is null for method " + method);
        }
    } catch (URIException e) {
        log.warn(e, e);
    }

}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

private void configureRequestForJson(HttpMethodBase request) {

    request.addRequestHeader("Accept", "application/json");

    if (request instanceof PutMethod)
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private void setHeaders(Map<Object, Object> properties, HttpMethodBase method) {
    method.setRequestHeader(HEADER_REQUEST_ACCEPT_ENCODING, "gzip"); //$NON-NLS-1$
    method.setRequestHeader(HEADER_REQUEST_USER_AGENT, USER_AGENT);

    /* Add Conditional GET Headers if present */
    if (properties != null) {
        String ifModifiedSince = (String) properties.get(IConnectionPropertyConstants.IF_MODIFIED_SINCE);
        String ifNoneMatch = (String) properties.get(IConnectionPropertyConstants.IF_NONE_MATCH);

        if (ifModifiedSince != null)
            method.setRequestHeader(HEADER_RESPONSE_IF_MODIFIED_SINCE, ifModifiedSince);

        if (ifNoneMatch != null)
            method.setRequestHeader(HEADER_RESPONSE_IF_NONE_MATCH, ifNoneMatch);
    }/*  w  w w .  j a v  a2 s .co m*/

    /* Add Accept-Language Header if present */
    if (properties != null && properties.containsKey(IConnectionPropertyConstants.ACCEPT_LANGUAGE))
        method.setRequestHeader(HEADER_REQUEST_ACCEPT_LANGUAGE,
                (String) properties.get(IConnectionPropertyConstants.ACCEPT_LANGUAGE));

    /* Add Cookie Header if present */
    if (properties != null && properties.containsKey(IConnectionPropertyConstants.COOKIE))
        method.setRequestHeader(HEADER_REQUEST_COOKIE,
                (String) properties.get(IConnectionPropertyConstants.COOKIE));

    /* Add more Headers */
    if (properties != null && properties.containsKey(IConnectionPropertyConstants.HEADERS)) {
        Map<?, ?> headers = (Map<?, ?>) properties.get(IConnectionPropertyConstants.HEADERS);
        Set<?> entries = headers.entrySet();
        for (Object obj : entries) {
            Entry<?, ?> entry = (Entry<?, ?>) obj;
            method.setRequestHeader((String) entry.getKey(), (String) entry.getValue());
        }
    }
}

From source file:org.sonar.wsclient.connectors.HttpClient3Connector.java

private void initRequest(HttpMethodBase request, AbstractQuery query) {
    request.setRequestHeader("Accept", "application/json");
    if (query.getLocale() != null) {
        request.setRequestHeader("Accept-Language", query.getLocale());
    }/*from  ww  w .j  a v  a2s  .  c o m*/
    request.getParams().setSoTimeout(query.getTimeoutMilliseconds());
}

From source file:org.sonarqube.ws.connectors.HttpClient3Connector.java

private void initRequest(HttpMethodBase request, AbstractQuery<?> query) {
    request.setRequestHeader("Accept", "application/json");
    if (query.getLocale() != null) {
        request.setRequestHeader("Accept-Language", query.getLocale());
    }//w  ww  . j a va  2  s. c om
    request.getParams().setSoTimeout(query.getTimeoutMilliseconds());
}

From source file:org.springfield.mojo.http.HttpHelper.java

/**
 * Sends a standard HTTP request to the specified URI using the determined method.
 * Attaches the content, uses the specified content type, sets cookies, timeout and
 * request headers/*from  ww w. j  a va  2s .co  m*/
 *  
 * @param method - the request method
 * @param uri - the uri to request
 * @param body - the content  
 * @param contentType - the content type
 * @param cookies - cookies
 * @param timeout - timeout in milliseconds
 * @param charSet - the character set
 * @param requestHeaders - extra user defined headers
 * @return response
 */
public static Response sendRequest(String method, String uri, String body, String contentType, String cookies,
        int timeout, String charSet, Map<String, String> requestHeaders) {
    // http client
    HttpClient client = new HttpClient();

    // method
    HttpMethodBase reqMethod = null;
    if (method.equals(HttpMethods.PUT)) {
        reqMethod = new PutMethod(uri);
    } else if (method.equals(HttpMethods.POST)) {
        reqMethod = new PostMethod(uri);
    } else if (method.equals(HttpMethods.GET)) {
        if (body != null) {
            // hack to be able to send a request body with a get (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "GET";
                }
            };
        } else {
            reqMethod = new GetMethod(uri);
        }
    } else if (method.equals(HttpMethods.DELETE)) {
        if (body != null) {
            // hack to be able to send a request body with a delete (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "DELETE";
                }
            };
        } else {
            reqMethod = new DeleteMethod(uri);
        }
    } else if (method.equals(HttpMethods.HEAD)) {
        reqMethod = new HeadMethod(uri);
    } else if (method.equals(HttpMethods.TRACE)) {
        reqMethod = new TraceMethod(uri);
    } else if (method.equals(HttpMethods.OPTIONS)) {
        reqMethod = new OptionsMethod(uri);
    }

    // add request body
    if (body != null) {
        try {
            RequestEntity entity = new StringRequestEntity(body, contentType, charSet);
            ((EntityEnclosingMethod) reqMethod).setRequestEntity(entity);
            reqMethod.setRequestHeader("Content-type", contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // add cookies
    if (cookies != null) {
        reqMethod.addRequestHeader("Cookie", cookies);
    }

    // add custom headers
    if (requestHeaders != null) {
        for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
            String name = header.getKey();
            String value = header.getValue();

            reqMethod.addRequestHeader(name, value);
        }
    }

    Response response = new Response();

    // do request
    try {
        if (timeout != -1) {
            client.getParams().setSoTimeout(timeout);
        }
        int statusCode = client.executeMethod(reqMethod);
        response.setStatusCode(statusCode);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // read response
    try {
        InputStream instream = reqMethod.getResponseBodyAsStream();
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int len;
        while ((len = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, len);
        }
        String resp = new String(outstream.toByteArray(), reqMethod.getResponseCharSet());
        response.setResponse(resp);

        //set content length
        long contentLength = reqMethod.getResponseContentLength();
        response.setContentLength(contentLength);
        //set character set
        String respCharSet = reqMethod.getResponseCharSet();
        response.setCharSet(respCharSet);
        //set all headers
        Header[] headers = reqMethod.getResponseHeaders();
        response.setHeaders(headers);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // release connection
    reqMethod.releaseConnection();

    // return
    return response;
}

From source file:org.wso2.carbon.appmgt.mdm.wso2mdm.MDMOperationsImpl.java

private boolean executeMethod(String tokenApiURL, String clientKey, String clientSecret, String authUser,
        String authPass, HttpClient httpClient, HttpMethodBase httpMethod) {
    String authKey = getAPIToken(tokenApiURL, clientKey, clientSecret, authUser, authPass, false);
    if (log.isDebugEnabled())
        log.debug("Access token received : " + authKey);
    //String authKey = "12345";
    try {/*from   ww  w  .j  a va 2s  .  c  o  m*/
        int statusCode = 401;
        int tries = 0;
        while (statusCode != 200) {
            if (log.isDebugEnabled())
                log.debug("Trying to call API : trying for " + (tries + 1) + " time(s)");
            httpMethod.setRequestHeader("Authorization", "Bearer " + authKey);
            if (log.isDebugEnabled())
                log.debug("Sending " + httpMethod.getName() + " request to " + httpMethod.getURI());
            statusCode = httpClient.executeMethod(httpMethod);
            if (log.isDebugEnabled())
                log.debug("Status code received : " + statusCode);

            if (++tries >= 3) {
                log.info("API Call failed for the 3rd time: No or Unauthorized Access Aborting...");
                return false;
            }
            if (statusCode == 401) {
                authKey = getAPIToken(tokenApiURL, clientKey, clientSecret, authUser, authPass, true);
                if (log.isDebugEnabled())
                    log.debug("Access token getting again, Access token received :  " + authKey + " in  try "
                            + tries);
            }

        }
        return true;
    } catch (IOException e) {
        String errorMessage = "No OK response received form the API";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        return false;
    }
}

From source file:org.wso2.carbon.identity.provisioning.connector.salesforce.SalesforceProvisioningConnector.java

/**
 * adding OAuth authorization headers to a httpMethod
 *
 * @param httpMethod method which wants to add Authorization header
 *///from w ww.  ja v  a  2  s. c  om
private void setAuthorizationHeader(HttpMethodBase httpMethod) throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    String accessToken = authenticate();
    if (StringUtils.isNotBlank(accessToken)) {
        httpMethod.setRequestHeader(SalesforceConnectorConstants.AUTHORIZATION_HEADER_NAME,
                SalesforceConnectorConstants.AUTHORIZATION_HEADER_OAUTH + " " + accessToken);

        if (isDebugEnabled) {
            log.debug("Setting authorization header for method : " + httpMethod.getName() + " as follows,");
            Header authorizationHeader = httpMethod
                    .getRequestHeader(SalesforceConnectorConstants.AUTHORIZATION_HEADER_NAME);
            log.debug(authorizationHeader.getName() + ": " + authorizationHeader.getValue());
        }
    } else {
        throw new IdentityProvisioningException("Authentication failed");
    }

}

From source file:org.wso2.carbon.identity.provisioning.connector.sample.SampleProvisioningConnector.java

/**
 * adding OAuth authorization headers to a httpMethod
 * /*from ww  w .  j  a v a 2  s  . com*/
 * @param httpMethod method which wants to add Authorization header
 */
private void setAuthorizationHeader(HttpMethodBase httpMethod) throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    String accessToken = authenticate();
    if (accessToken != null && !accessToken.isEmpty()) {
        httpMethod.setRequestHeader(SampleConnectorConstants.AUTHORIZATION_HEADER_NAME,
                SampleConnectorConstants.AUTHORIZATION_HEADER_OAUTH + " " + accessToken);

        if (isDebugEnabled) {
            log.debug("Setting authorization header for method : " + httpMethod.getName() + " as follows,");
            Header authorizationHeader = httpMethod
                    .getRequestHeader(SampleConnectorConstants.AUTHORIZATION_HEADER_NAME);
            log.debug(authorizationHeader.getName() + ": " + authorizationHeader.getValue());
        }
    } else {
        throw new IdentityProvisioningException("Authentication failed");
    }

}

From source file:org.zend.php.zendserver.deployment.core.targets.OpenShiftTargetInitializer.java

private HttpMethodBase setCookies(HttpMethodBase method, Map<String, String> params) {
    if (params != null) {
        StringBuilder builder = new StringBuilder();
        Set<String> keyList = params.keySet();
        for (String key : keyList) {
            builder.append(key);// ww  w  . ja v a  2s  . c o  m
            builder.append("="); //$NON-NLS-1$
            builder.append(params.get(key));
            builder.append(";"); //$NON-NLS-1$
        }
        String value = builder.toString();
        if (value.length() > 0) {
            value = value.substring(0, value.length() - 1);
            method.setRequestHeader("Cookie", value); //$NON-NLS-1$
        }
    }
    return method;
}