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(String paramString1, String paramString2);

Source Link

Usage

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private void setHeaders(HttpMethod method, String groupId, String userId) {
    if (userId != null)
        if (!userId.equals(""))
            method.addRequestHeader(SchedulerDictionary.X_BONFIRE_ASSERTED_ID, userId);

    if (groupId != null)
        if (!groupId.equals(""))
            method.addRequestHeader(SchedulerDictionary.X_BONFIRE_GROUPS_ID, groupId);

    method.addRequestHeader("User-Agent", SchedulerDictionary.USER_AGENT);
    method.addRequestHeader("Accept", SchedulerDictionary.ACCEPT);
}

From source file:edu.unc.lib.dl.admin.controller.RESTProxyController.java

@RequestMapping(value = { "/services/rest", "/services/rest/*", "/services/rest/**/*" })
public final void proxyAjaxCall(HttpServletRequest request, HttpServletResponse response) throws IOException {
    log.debug("Prepending service url " + this.servicesUrl + " to " + request.getRequestURI());
    String url = request.getRequestURI().replaceFirst(".*/services/rest/?", this.servicesUrl);
    if (request.getQueryString() != null)
        url = url + "?" + request.getQueryString();

    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    HttpClient client = new HttpClient();
    HttpMethod method = null;
    try {//  w  ww  . j  a v a2  s  .c  om
        log.debug("Proxying ajax request to services REST api via " + request.getMethod());
        // Split this according to the type of request
        if (request.getMethod().equals("GET")) {
            method = new GetMethod(url);
        } else if (request.getMethod().equals("POST")) {
            method = new PostMethod(url);
            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Forward the user's groups along with the request
        method.addRequestHeader(HttpClientUtil.SHIBBOLETH_GROUPS_HEADER, GroupsThreadStore.getGroupString());
        method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername());

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }
        try (InputStream responseStream = method.getResponseBodyAsStream()) {
            int b;
            while ((b = responseStream.read()) != -1) {
                response.getOutputStream().write(b);
            }
        }
        response.getOutputStream().flush();
    } catch (HttpException e) {
        writer.write(e.toString());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        writer.write(e.toString());
        throw e;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }/*  www . ja  v a 2 s.  co  m*/
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // HttpMethod
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }/*from ww  w  .j a v a 2s  .  c o  m*/
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:net.oauth.client.httpclient3.HttpClient3.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();//w  w w  .j a  v  a  2 s. com
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}

From source file:net.adamcin.httpsig.http.apache3.Http3SignatureAuthScheme.java

public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    if (credentials instanceof SignerCredentials) {
        SignerCredentials creds = (SignerCredentials) credentials;
        String headers = this.getParameter(Constants.HEADERS);
        String algorithms = this.getParameter(Constants.ALGORITHMS);

        Challenge challenge = new Challenge(this.getRealm(), Constants.parseTokens(headers),
                Challenge.parseAlgorithms(algorithms));

        Signer signer = creds.getSigner();
        if (signer != null) {

            if (this.rotate) {
                this.rotate = false;
                if (!signer.rotateKeys(challenge, this.lastAuthz)) {
                    signer.rotateKeys(challenge);
                    return null;
                }//  w  w  w . j av a 2s  . com
            }

            RequestContent.Builder sigBuilder = new RequestContent.Builder();

            sigBuilder.setRequestTarget(method.getName(),
                    method.getPath() + (method.getQueryString() != null ? "?" + method.getQueryString() : ""));

            for (Header header : method.getRequestHeaders()) {
                sigBuilder.addHeader(header.getName(), header.getValue());
            }

            if (sigBuilder.build().getDate() == null) {
                sigBuilder.addDateNow();
                method.addRequestHeader(Constants.HEADER_DATE, sigBuilder.build().getDate());
            }

            Authorization authorization = creds.getSigner().sign(sigBuilder.build());
            this.lastAuthz = authorization;
            if (authorization != null) {
                return authorization.getHeaderValue();
            }
        }
    }

    return null;
}

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureAckHttpMethod(HttpMethod httpMethod, long onceTimeOut) {
    // appName/*w  ww .  jav  a 2  s  .  co m*/
    if (null != this.appName) {
        httpMethod.addRequestHeader(Constants.APPNAME, this.appName);
    }
    httpMethod.addRequestHeader(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION);

    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);

    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

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

/**
 * Apply any applicable header overrides to request
 *
 * @param httpMethodProxyRequest//from  w  w w .  j  a  v  a 2 s  .co m
 * @throws Exception
 */
private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {
    for (EndpointOverride selectedPath : requestInformation.get().selectedRequestPaths) {
        List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();
        for (EnabledEndpoint endpoint : points) {
            if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {
                httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),
                        endpoint.getArguments()[1].toString());
                requestInformation.get().modified = true;
            } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {
                httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());
                requestInformation.get().modified = true;
            }
        }
    }
}

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }/*  w  w w  .j a va2 s .co  m*/
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }
    // appName
    if (null != this.appName) {
        httpMethod.addRequestHeader(Constants.APPNAME, this.appName);
    }
    httpMethod.addRequestHeader(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION);

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:gov.loc.ndmso.proxyfilter.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;/*ww w.  j  ava2s  .  c o m*/
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else {
        // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    @SuppressWarnings("unchecked")
    Enumeration<String> e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            @SuppressWarnings("unchecked")
            Enumeration<String> values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = values.nextElement();
                // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    // add rs5/tomcat5 request header for ML
    method.addRequestHeader("X-Via", "tomcat5");

    // log.info("proxy query string " + method.getQueryString());
    return method;
}