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

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

Introduction

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

Prototype

public abstract void addRequestHeader(Header paramHeader);

Source Link

Usage

From source file:com.bonitasoft.connector.Trello_Get_BoardImpl.java

@Override
protected void executeBusinessLogic() throws ConnectorException {
    // Get access to the connector input parameters
    // getBoard();
    // getToken();
    // getApiKey();
    HttpMethod method = null;
    try {//from   w w  w .  ja v a 2 s .  c o  m
        HttpClient client = new HttpClient();
        method = new GetMethod(String.format(GET_TRELLO_BOARD_URL, getBoard(), getApiKey(), getToken()));
        method.addRequestHeader(new Header("Content-Type", "application/json; charset=UTF-8"));
        client.executeMethod(method);
        JSONArray array = getJSONFromResponse(method);

        List<Map<String, Object>> result = generateBaseStructure(array);
        setTrelloList(result);
        setBonitaColumn(TITLES);
        setBonitaList(getBonitaTableList(result));
        setStringCSV(generateCSVFromList(result));
    } catch (Exception e) {
        throw new ConnectorException(e.getMessage());
    } finally {
        try {
            method.releaseConnection();
        } catch (Exception e) {
            logger.severe("There is a problem releasing Trello Connection");
        }
    }
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request) throws IOException {
    URI targetUri;/*  w  w w .ja  v  a2 s  .  c om*/
    try {
        targetUri = new URI(uriEncode(targetUrl));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HttpMethod commonsHttpMethod = httpMethodProvider.getMethod(request.getMethod(), targetUri.toString());

    commonsHttpMethod.setFollowRedirects(false);

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerVals = request.getHeaders(headerName);
        while (headerVals.hasMoreElements()) {
            String headerValue = headerVals.nextElement();
            headerValue = headerFilter.processRequestHeader(headerName, headerValue);
            if (headerValue != null) {
                commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue));
            }

        }
    }

    return commonsHttpMethod;
}

From source file:com.groupon.odo.Proxy.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*from  w w w.  j  a  va  2s.  co m*/
 *
 * @param httpServletRequest     The request object representing the client's request to the
 *                               servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest)
        throws Exception {

    String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME))
            continue;

        logger.info("Current header: {}", stringHeaderName);
        // As per the Java Servlet API 2.5 documentation:
        // Some headers, such as Accept-Language can be sent by clients
        // as several headers each with a different value rather than
        // sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the
        // client
        Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);

        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) && requestInformation.get().handle) {
                String hostValue = getHostHeaderForHost(hostName);
                if (hostValue != null) {
                    stringHeaderValue = hostValue;
                }
            }

            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.addRequestHeader(header);
        }
    }

    // bail if we aren't fully handling this request
    if (!requestInformation.get().handle) {
        return;
    }

    // deal with header overrides for the request
    processRequestHeaderOverrides(httpMethodProxyRequest);
}

From source file:edu.ucsb.eucalyptus.cloud.ws.WalrusManager.java

public static void callWalrusHeartBeat(String account, String instid, String API) throws Throwable {
    HttpClient client = null;/*from w w w.  j  av a  2 s .  c om*/
    HttpMethod method = null;
    NameValuePair[] queryString = null;
    if (account == null || instid == null) {
        LOG.debug(API + ":callWalrusHeartBeat error: #account=" + account + "#instid=" + instid + "#");
        return;
    }
    try {
        client = new HttpClient();
        String URL = "http://127.0.0.1/sbx_svr/rest/EBS/walrusheartbeat";
        queryString = new NameValuePair[] { new NameValuePair("account", account),
                new NameValuePair("instanceid", instid) };
        method = new PostMethod(URL);
        method.addRequestHeader(new Header("Connection", "close"));
        method.setQueryString(queryString);
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            // Read the response body.
            StringBuffer stb = new StringBuffer();
            InputStream ins = method.getResponseBodyAsStream();
            InputStreamReader insReader = new InputStreamReader(ins);
            BufferedReader br = new BufferedReader(insReader);
            String buffText = br.readLine();
            while (null != buffText) {
                stb.append(buffText);
                buffText = br.readLine();
            }
            if (stb.length() == 0 || StringUtils.isEmpty(stb.toString())) {
                LOG.debug(API + ":callWalrusHeartBeat: Http Response Body is empty!");
            }
        } else {
            LOG.debug(API + ":callWalrusHeartBeat: Http Response Error:" + statusCode + "#account=" + account
                    + "#instid=" + instid);
        }
    } catch (Throwable t) {
        LOG.debug(API + ":callWalrusHeartBeat: Http Response Error: #account=" + account + "#instid=" + instid
                + "#" + t.toString());
        throw t;
    } finally {
        try {
            if (method != null)
                method.releaseConnection();
        } catch (Throwable t) {
            /*NOP*/}
        ;
    }
}

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

public void addCustomHeaders(HttpMethod method, MessageContext msgContext) {

    boolean isCustomUserAgentSet = false;
    // set the custom headers, if available
    Object httpHeadersObj = msgContext.getProperty(HTTPConstants.HTTP_HEADERS);
    if (httpHeadersObj != null) {
        if (httpHeadersObj instanceof ArrayList) {
            ArrayList httpHeaders = (ArrayList) httpHeadersObj;
            Header header;/*from  www.ja  v  a2 s .  c o m*/
            for (int i = 0; i < httpHeaders.size(); i++) {
                header = (Header) httpHeaders.get(i);
                if (HTTPConstants.HEADER_USER_AGENT.equals(header.getName())) {
                    isCustomUserAgentSet = true;
                }
                method.addRequestHeader(header);
            }

        }
        if (httpHeadersObj instanceof Map) {
            Map httpHeaders = (Map) httpHeadersObj;
            for (Iterator iterator = httpHeaders.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                if (HTTPConstants.HEADER_USER_AGENT.equals(key)) {
                    isCustomUserAgentSet = true;
                }
                method.addRequestHeader(key, value);
            }
        }
    }

    // we have to consider the TRANSPORT_HEADERS map as well
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (transportHeaders != null) {
        removeUnwantedHeaders(msgContext);

        Set headerEntries = transportHeaders.entrySet();

        for (Object headerEntry : headerEntries) {
            if (headerEntry instanceof Map.Entry) {
                Header[] headers = method.getRequestHeaders();

                boolean headerAdded = false;
                for (Header header : headers) {
                    if (header.getName() != null) {
                        Object headerKey = ((Map.Entry) headerEntry).getKey();
                        if (headerKey instanceof String
                                && header.getName().equalsIgnoreCase((String) headerKey)) {
                            // According to RFC2626 http headers are case insensitive.
                            // So need to ignore case
                            headerAdded = true;
                            break;
                        }
                    }
                }

                if (!headerAdded) {
                    method.addRequestHeader(((Map.Entry) headerEntry).getKey().toString(),
                            ((Map.Entry) headerEntry).getValue().toString());
                }
            }
        }
    }

    if (!isCustomUserAgentSet) {
        String userAgentString = getUserAgent(msgContext);
        method.setRequestHeader(HTTPConstants.HEADER_USER_AGENT, userAgentString);
    }

}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

public void addCustomHeaders(HttpMethod method, MessageContext msgContext) {

    boolean isCustomUserAgentSet = false;
    // set the custom headers, if available
    Object httpHeadersObj = msgContext.getProperty(HTTPConstants.HTTP_HEADERS);
    if (httpHeadersObj != null) {
        if (httpHeadersObj instanceof List) {
            List httpHeaders = (List) httpHeadersObj;
            for (int i = 0; i < httpHeaders.size(); i++) {
                NamedValue nv = (NamedValue) httpHeaders.get(i);
                if (nv != null) {
                    Header header = new Header(nv.getName(), nv.getValue());
                    if (HTTPConstants.HEADER_USER_AGENT.equals(header.getName())) {
                        isCustomUserAgentSet = true;
                    }//from ww w.ja  v  a 2s. co  m
                    method.addRequestHeader(header);
                }
            }

        }
        if (httpHeadersObj instanceof Map) {
            Map httpHeaders = (Map) httpHeadersObj;
            for (Iterator iterator = httpHeaders.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                if (HTTPConstants.HEADER_USER_AGENT.equals(key)) {
                    isCustomUserAgentSet = true;
                }
                method.addRequestHeader(key, value);
            }
        }
    }

    // we have to consider the TRANSPORT_HEADERS map as well
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (transportHeaders != null) {
        removeUnwantedHeaders(msgContext);

        Set headerEntries = transportHeaders.entrySet();

        for (Object headerEntry : headerEntries) {
            if (headerEntry instanceof Map.Entry) {
                Header[] headers = method.getRequestHeaders();

                boolean headerAdded = false;
                for (Header header : headers) {
                    if (header.getName() != null
                            && header.getName().equals(((Map.Entry) headerEntry).getKey())) {
                        headerAdded = true;
                        break;
                    }
                }

                if (!headerAdded) {
                    method.addRequestHeader(((Map.Entry) headerEntry).getKey().toString(),
                            ((Map.Entry) headerEntry).getValue().toString());
                }
            }
        }
    }

    if (!isCustomUserAgentSet) {
        String userAgentString = getUserAgent(msgContext);
        method.setRequestHeader(HTTPConstants.HEADER_USER_AGENT, userAgentString);
    }

}

From source file:org.apache.hadoop.hbase.stargate.client.Client.java

/**
 * Execute a transaction method given a complete URI.
 * @param method the transaction method//  www  .j a  v  a 2  s. c om
 * @param headers HTTP header values to send
 * @param uri the URI
 * @return the HTTP response code
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException {
    method.setURI(new URI(uri));
    if (headers != null) {
        for (Header header : headers) {
            method.addRequestHeader(header);
        }
    }
    long startTime = System.currentTimeMillis();
    int code = httpClient.executeMethod(method);
    long endTime = System.currentTimeMillis();
    if (LOG.isDebugEnabled()) {
        LOG.debug(method.getName() + " " + uri + ": " + code + " " + method.getStatusText() + " in "
                + (endTime - startTime) + " ms");
    }
    return code;
}

From source file:org.apache.webdav.ant.Utils.java

public static void generateIfHeader(HttpMethod method, String lockToken) {
    if (lockToken != null) {
        Header ifHeader = new Header();
        ifHeader.setName("If");
        ifHeader.setValue("(<" + lockToken + ">)");
        method.addRequestHeader(ifHeader);
    }//from ww  w.j  a  v  a2s .com
}

From source file:org.apache.wink.itest.cachetest.NewsHttpClient.java

void setRequestHeaders(HttpMethod method) {
    if (requestHeaders != null) {
        for (Header header : requestHeaders) {
            method.addRequestHeader(header);
        }/*from   ww w. j  a v a 2  s.c  o  m*/
    }
}

From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.CreateFolderCommand.java

private void configureHttpMethod(HttpMethod method) {
    method.addRequestHeader(new Header("Authorization", cfLauncherAuth));
}