Example usage for org.apache.http.client.methods HttpRequestBase addHeader

List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase addHeader.

Prototype

public void addHeader(String str, String str2) 

Source Link

Usage

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

private void addAuth(HttpRequestBase method, @Nonnull String token) throws CloudException, InternalException {
    if (matches(getAPIVersion(), "0.8", "0.8")) {
        method.addHeader("Cookie", "vcloud-token=" + token);
    } else {//from ww w  .  j  av  a 2  s.  c  om
        method.addHeader("x-vcloud-authorization", token);
    }
}

From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java

/**
 * Returns the request that points to the backend service defined by the provided 
 * <code>urlToService</code> URL. The headers of the origin request are copied to 
 * the backend request, except of "host" and "content-length".   
 * /* www  .  j  a v a2  s .  co m*/
 * @param request
 *            original request to the Web application
 * @param urlToService
 *            URL to the targeted backend service
 * @return initialized backend service request
 * @throws IOException 
 */
private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException {
    String method = request.getMethod();
    LOGGER.debug("HTTP method: " + method);

    HttpRequestBase backendRequest = null;
    if (HttpPost.METHOD_NAME.equals(method)) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipe(request.getInputStream(), out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        entity.setContentType(request.getHeader("Content-Type"));
        HttpPost post = new HttpPost(urlToService);
        post.setEntity(entity);
        backendRequest = post;
    } else if (HttpGet.METHOD_NAME.equals(method)) {
        HttpGet get = new HttpGet(urlToService);
        backendRequest = get;
    } else if (HttpPut.METHOD_NAME.equals(method)) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipe(request.getInputStream(), out);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        entity.setContentType(request.getHeader("Content-Type"));
        HttpPut put = new HttpPut(urlToService);
        put.setEntity(entity);
        backendRequest = put;
    } else if (HttpDelete.METHOD_NAME.equals(method)) {
        HttpDelete delete = new HttpDelete(urlToService);
        backendRequest = delete;
    }

    // copy headers from Web application request to backend request, while
    // filtering the blocked headers

    LOGGER.debug("backend request headers:");

    Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS));

    Enumeration<String> setCookieHeaders = request.getHeaders("Cookie");
    while (setCookieHeaders.hasMoreElements()) {
        String cookieHeader = setCookieHeaders.nextElement();
        if (blockedHeaders.contains(cookieHeader.toLowerCase())) {
            String replacedCookie = removeJSessionID(cookieHeader);
            backendRequest.addHeader("Cookie", replacedCookie);
        }
        LOGGER.debug("Cookie header => " + cookieHeader);
    }

    for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
        String headerName = e.nextElement().toString();
        if (!blockedHeaders.contains(headerName.toLowerCase())) {
            backendRequest.addHeader(headerName, request.getHeader(headerName));
            LOGGER.debug("    => " + headerName + ": " + request.getHeader(headerName));
        } else {
            LOGGER.debug("    => " + headerName + ": blocked request header");
        }
    }

    return backendRequest;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

protected HttpRequestBase getMethod(@Nonnull String httpMethod, @Nonnull String endpoint,
        @Nonnull Map<String, String> queryParams, @Nullable Map<String, String> headers, boolean authorization)
        throws CloudException, InternalException {
    HttpRequestBase method;// w  w w .jav a2s  .c o  m

    if (httpMethod.equals("GET")) {
        method = new HttpGet(endpoint);
    } else if (httpMethod.equals("POST")) {
        method = new HttpPost(endpoint);
    } else if (httpMethod.equals("PUT")) {
        method = new HttpPut(endpoint);
    } else if (httpMethod.equals("DELETE")) {
        method = new HttpDelete(endpoint);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpHead(endpoint);
    } else if (httpMethod.equals("OPTIONS")) {
        method = new HttpOptions(endpoint);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpTrace(endpoint);
    } else {
        method = new HttpGet(endpoint);
    }
    if (!authorization) {
        return method;
    }
    if (headers == null) {
        headers = new TreeMap<String, String>();
    }

    String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
    DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN);

    rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));
    headers.put("Date", rfc1123Format.format(new Date()));
    headers.put(Header_Prefix_MS + "version", VERSION);
    for (String key : headers.keySet()) {
        method.addHeader(key, headers.get(key));
    }

    if (method.getFirstHeader("content-type") == null && !httpMethod.equals("GET")) {
        method.addHeader("content-type", "application/xml;charset=utf-8");
    }
    method.addHeader("Authorization", "SharedKeyLite " + getStorageAccount() + ":"
            + calculatedSharedKeyLiteSignature(method, queryParams));
    return method;
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);//w w  w .  j  a  v  a  2s  .com
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:org.apache.solr.servlet.HttpSolrCall.java

private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException {
    HttpRequestBase method = null;/* w w  w  . j a v  a2  s.c  o  m*/
    HttpEntity httpEntity = null;
    try {
        String urlstr = coreUrl + queryParams.toQueryString();

        boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod());
        if ("GET".equals(req.getMethod())) {
            method = new HttpGet(urlstr);
        } else if ("HEAD".equals(req.getMethod())) {
            method = new HttpHead(urlstr);
        } else if (isPostOrPutRequest) {
            HttpEntityEnclosingRequestBase entityRequest = "POST".equals(req.getMethod()) ? new HttpPost(urlstr)
                    : new HttpPut(urlstr);
            InputStream in = new CloseShieldInputStream(req.getInputStream()); // Prevent close of container streams
            HttpEntity entity = new InputStreamEntity(in, req.getContentLength());
            entityRequest.setEntity(entity);
            method = entityRequest;
        } else if ("DELETE".equals(req.getMethod())) {
            method = new HttpDelete(urlstr);
        } else {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unexpected method type: " + req.getMethod());
        }

        for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = e.nextElement();
            if (!"host".equalsIgnoreCase(headerName) && !"authorization".equalsIgnoreCase(headerName)
                    && !"accept".equalsIgnoreCase(headerName)) {
                method.addHeader(headerName, req.getHeader(headerName));
            }
        }
        // These headers not supported for HttpEntityEnclosingRequests
        if (method instanceof HttpEntityEnclosingRequest) {
            method.removeHeaders(TRANSFER_ENCODING_HEADER);
            method.removeHeaders(CONTENT_LENGTH_HEADER);
        }

        final HttpResponse response = solrDispatchFilter.httpClient.execute(method,
                HttpClientUtil.createNewHttpClientRequestContext());
        int httpStatus = response.getStatusLine().getStatusCode();
        httpEntity = response.getEntity();

        resp.setStatus(httpStatus);
        for (HeaderIterator responseHeaders = response.headerIterator(); responseHeaders.hasNext();) {
            Header header = responseHeaders.nextHeader();

            // We pull out these two headers below because they can cause chunked
            // encoding issues with Tomcat
            if (header != null && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER)
                    && !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) {
                resp.addHeader(header.getName(), header.getValue());
            }
        }

        if (httpEntity != null) {
            if (httpEntity.getContentEncoding() != null)
                resp.setCharacterEncoding(httpEntity.getContentEncoding().getValue());
            if (httpEntity.getContentType() != null)
                resp.setContentType(httpEntity.getContentType().getValue());

            InputStream is = httpEntity.getContent();
            OutputStream os = resp.getOutputStream();

            IOUtils.copyLarge(is, os);
        }

    } catch (IOException e) {
        sendError(new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error trying to proxy request for url: " + coreUrl, e));
    } finally {
        Utils.consumeFully(httpEntity);
    }

}

From source file:com.google.acre.script.AcreFetch.java

@SuppressWarnings("boxing")
public void fetch(boolean system, String response_encoding, boolean log_to_user, boolean no_redirect) {

    if (request_url.length() > 2047) {
        throw new AcreURLFetchException("fetching URL failed - url is too long");
    }/*from   w w  w .  ja  v  a2s.  c o m*/

    DefaultHttpClient client = new DefaultHttpClient(_connectionManager, null);

    HttpParams params = client.getParams();

    // pass the deadline down to the invoked service.
    // this will be ignored unless we are fetching from another
    // acre server.
    // note that we may send a deadline that is already passed:
    // it's not our job to throw here since we don't know how
    // the target service will interpret the quota header.
    // NOTE: this is done *after* the user sets the headers to overwrite
    // whatever settings they might have tried to change for this value
    // (which could be a security hazard)
    long sub_deadline = (HostEnv.LIMIT_EXECUTION_TIME) ? _deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE
            : System.currentTimeMillis() + HostEnv.ACRE_URLFETCH_TIMEOUT;
    int reentries = _reentries + 1;
    request_headers.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentries);

    // if this is not an internal call, we need to invoke the call thru a proxy
    if (!_internal) {
        // XXX No sense wasting the resources to gzip inside the network.
        // XXX seems that twitter gets upset when we do this
        /*
        if (!request_headers.containsKey("accept-encoding")) {
        request_headers.put("accept-encoding", "gzip");
        }
        */
        String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue();
        int proxy_port = -1;
        if (!(proxy_host.length() == 0)) {
            proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger();
            HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http");
            params.setParameter(AllClientPNames.DEFAULT_PROXY, proxy);
        }
    }

    params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // in msec

    long timeout = _deadline - System.currentTimeMillis();
    if (timeout < 0)
        timeout = 0;
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, (int) timeout);
    params.setParameter(AllClientPNames.SO_TIMEOUT, (int) timeout);

    // we're not streaming the request so this should be a win.
    params.setParameter(AllClientPNames.TCP_NODELAY, true);

    // reuse an existing socket if it is in TIME_WAIT state.
    params.setParameter(AllClientPNames.SO_REUSEADDR, true);

    // set the encoding of our POST payloads to UTF-8
    params.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    BasicCookieStore cstore = new BasicCookieStore();
    for (AcreCookie cookie : request_cookies.values()) {
        cstore.addCookie(cookie.toClientCookie());
    }
    client.setCookieStore(cstore);

    HttpRequestBase method;

    HashMap<String, String> logmsg = new HashMap<String, String>();
    logmsg.put("Method", request_method);
    logmsg.put("URL", request_url);

    params.setParameter(AllClientPNames.HANDLE_REDIRECTS, !no_redirect);
    logmsg.put("Redirect", Boolean.toString(!no_redirect));

    try {
        if (request_method.equals("GET")) {
            method = new HttpGet(request_url);
        } else if (request_method.equals("POST")) {
            method = new HttpPost(request_url);
        } else if (request_method.equals("HEAD")) {
            method = new HttpHead(request_url);
        } else if (request_method.equals("PUT")) {
            method = new HttpPut(request_url);
        } else if (request_method.equals("DELETE")) {
            method = new HttpDelete(request_url);
        } else if (request_method.equals("PROPFIND")) {
            method = new HttpPropFind(request_url);
        } else {
            throw new AcreURLFetchException("Failed: unsupported (so far) method " + request_method);
        }
        method.getParams().setBooleanParameter(AllClientPNames.USE_EXPECT_CONTINUE, false);
    } catch (java.lang.IllegalArgumentException e) {
        throw new AcreURLFetchException("Unable to fetch URL; this is most likely an issue with URL encoding.");
    } catch (java.lang.IllegalStateException e) {
        throw new AcreURLFetchException("Unable to fetch URL; possibly an illegal protocol?");
    }

    StringBuilder request_header_log = new StringBuilder();
    for (Map.Entry<String, String> header : request_headers.entrySet()) {
        String key = header.getKey();
        String value = header.getValue();

        // XXX should suppress cookie headers?
        // content-type and length?

        if ("content-type".equalsIgnoreCase(key)) {
            Matcher m = contentTypeCharsetPattern.matcher(value);
            if (m.find()) {
                content_type = m.group(1);
                content_type_charset = m.group(2);
            } else {
                content_type_charset = "utf-8";
            }
            method.addHeader(key, value);
        } else if ("content-length".equalsIgnoreCase(key)) {
            // ignore user-supplied content-length, which is
            // probably wrong due to chars vs bytes and is
            // redundant anyway
            ArrayList<String> msg = new ArrayList<String>();
            msg.add("User-supplied content-length header is ignored");
            _acre_response.log("warn", msg);
        } else if ("user-agent".equalsIgnoreCase(key)) {
            params.setParameter(AllClientPNames.USER_AGENT, value);
        } else {
            method.addHeader(key, value);
        }
        if (!("x-acre-auth".equalsIgnoreCase(key))) {
            request_header_log.append(key + ": " + value + "\r\n");
        }
    }
    logmsg.put("Headers", request_header_log.toString());

    // XXX need more detailed error checking
    if (method instanceof HttpEntityEnclosingRequestBase && request_body != null) {

        HttpEntityEnclosingRequestBase em = (HttpEntityEnclosingRequestBase) method;
        try {
            if (request_body instanceof String) {
                StringEntity ent = new StringEntity((String) request_body, content_type_charset);
                em.setEntity(ent);
            } else if (request_body instanceof JSBinary) {
                ByteArrayEntity ent = new ByteArrayEntity(((JSBinary) request_body).get_data());
                em.setEntity(ent);
            }
        } catch (UnsupportedEncodingException e) {
            throw new AcreURLFetchException(
                    "Failed to fetch URL. " + " - Unsupported charset: " + content_type_charset);
        }
    }

    if (!system && log_to_user) {
        ArrayList<Object> msg = new ArrayList<Object>();
        msg.add("urlfetch request");
        msg.add(logmsg);
        _acre_response.log("debug", msg);
    }
    _logger.info("urlfetch.request", logmsg);

    long startTime = System.currentTimeMillis();

    try {
        // this sends the http request and waits
        HttpResponse hres = client.execute(method);
        status = hres.getStatusLine().getStatusCode();
        HashMap<String, String> res_logmsg = new HashMap<String, String>();
        res_logmsg.put("URL", request_url);
        res_logmsg.put("Status", ((Integer) status).toString());

        Header content_type_header = null;

        // translate response headers
        StringBuilder response_header_log = new StringBuilder();
        Header[] rawheaders = hres.getAllHeaders();
        for (Header rawheader : rawheaders) {
            String headername = rawheader.getName().toLowerCase();
            if (headername.equalsIgnoreCase("content-type")) {
                content_type_header = rawheader;
                // XXX should strip everything after ;
                content_type = rawheader.getValue();

                // XXX don't set content_type_parameters, deprecated?
            } else if (headername.equalsIgnoreCase("x-metaweb-cost")) {
                _costCollector.merge(rawheader.getValue());
            } else if (headername.equalsIgnoreCase("x-metaweb-tid")) {
                res_logmsg.put("ITID", rawheader.getValue());
            }

            headers.put(headername, rawheader.getValue());
            response_header_log.append(headername + ": " + rawheader.getValue() + "\r\n");
        }

        res_logmsg.put("Headers", response_header_log.toString());

        if (!system && log_to_user) {
            ArrayList<Object> msg = new ArrayList<Object>();
            msg.add("urlfetch response");
            msg.add(res_logmsg);
            _acre_response.log("debug", msg);
        }

        _logger.info("urlfetch.response", res_logmsg);

        // read cookies
        for (Cookie c : cstore.getCookies()) {
            cookies.put(c.getName(), new AcreCookie(c));
        }

        // get body encoding

        String charset = null;
        if (content_type_header != null) {
            HeaderElement values[] = content_type_header.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
        }

        if (charset == null)
            charset = response_encoding;

        // read body
        HttpEntity ent = hres.getEntity();
        if (ent != null) {
            InputStream res_stream = ent.getContent();
            Header cenc = ent.getContentEncoding();
            if (cenc != null && res_stream != null) {
                HeaderElement[] codecs = cenc.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        res_stream = new GZIPInputStream(res_stream);
                    }
                }
            }

            long firstByteTime = 0;
            long endTime = 0;
            if (content_type != null
                    && (content_type.startsWith("image/") || content_type.startsWith("application/octet-stream")
                            || content_type.startsWith("multipart/form-data"))) {
                // HttpClient's InputStream doesn't support mark/reset, so
                // wrap it with one that does.
                BufferedInputStream bufis = new BufferedInputStream(res_stream);
                bufis.mark(2);
                bufis.read();
                firstByteTime = System.currentTimeMillis();
                bufis.reset();
                byte[] data = IOUtils.toByteArray(bufis);

                endTime = System.currentTimeMillis();
                body = new JSBinary();
                ((JSBinary) body).set_data(data);

                try {
                    if (res_stream != null) {
                        res_stream.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            } else if (res_stream == null || charset == null) {
                firstByteTime = endTime = System.currentTimeMillis();
                body = "";
            } else {
                StringWriter writer = new StringWriter();
                Reader reader = new InputStreamReader(res_stream, charset);
                int i = reader.read();
                firstByteTime = System.currentTimeMillis();
                writer.write(i);
                IOUtils.copy(reader, writer);
                endTime = System.currentTimeMillis();
                body = writer.toString();

                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            long waitingTime = firstByteTime - startTime;
            long readingTime = endTime - firstByteTime;

            _logger.debug("urlfetch.timings", "waiting time: " + waitingTime + "ms");
            _logger.debug("urlfetch.timings", "reading time: " + readingTime + "ms");

            Statistics.instance().collectUrlfetchTime(startTime, firstByteTime, endTime);

            _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waitingTime)
                    .collect((system) ? "asub" : "auub", waitingTime);
        }
    } catch (IllegalArgumentException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("failed to fetch URL. " + " - Request Error: " + cause.getMessage());
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage());
    } catch (RuntimeException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage());
    } finally {
        method.abort();
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * Extracts all the required non-cookie headers for that particular URL request and
 * sets them in the <code>HttpMethod</code> passed in
 *
 * @param request/*from w  ww.j av a  2s .  c o  m*/
 *            <code>HttpRequest</code> which represents the request
 * @param url
 *            <code>URL</code> of the URL request
 * @param headerManager
 *            the <code>HeaderManager</code> containing all the cookies
 *            for this <code>UrlConfig</code>
 * @param cacheManager the CacheManager (may be null)
 */
protected void setConnectionHeaders(HttpRequestBase request, URL url, HeaderManager headerManager,
        CacheManager cacheManager) {
    if (headerManager != null) {
        CollectionProperty headers = headerManager.getHeaders();
        if (headers != null) {
            for (JMeterProperty jMeterProperty : headers) {
                org.apache.jmeter.protocol.http.control.Header header = (org.apache.jmeter.protocol.http.control.Header) jMeterProperty
                        .getObjectValue();
                String n = header.getName();
                // Don't allow override of Content-Length
                // TODO - what other headers are not allowed?
                if (!HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(n)) {
                    String v = header.getValue();
                    if (HTTPConstants.HEADER_HOST.equalsIgnoreCase(n)) {
                        int port = getPortFromHostHeader(v, url.getPort());
                        v = v.replaceFirst(":\\d+$", ""); // remove any port specification // $NON-NLS-1$ $NON-NLS-2$
                        if (port != -1) {
                            if (port == url.getDefaultPort()) {
                                port = -1; // no need to specify the port if it is the default
                            }
                        }
                        request.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(v, port));
                    } else {
                        request.addHeader(n, v);
                    }
                }
            }
        }
    }
    if (cacheManager != null) {
        cacheManager.setHeaders(url, request);
    }
}

From source file:nl.nn.adapterframework.extensions.cmis.CmisHttpSender.java

@Override
public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList pvl,
        Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException {
    HttpRequestBase method = null;

    try {//  w  w w.  j a va2 s .c o  m
        if (getMethodType().equals("GET")) {
            method = new HttpGet(uri.build());
        } else if (getMethodType().equals("POST")) {
            HttpPost httpPost = new HttpPost(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPost.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPost.setEntity(entity);
                out.close();

                method = httpPost;
            }
        } else if (getMethodType().equals("PUT")) {
            HttpPut httpPut = new HttpPut(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPut.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPut.setEntity(entity);
                out.close();

                method = httpPut;
            }
        } else if (getMethodType().equals("DELETE")) {
            method = new HttpDelete(uri.build());
        } else {
            throw new MethodNotSupportedException("method [" + getMethodType() + "] not implemented");
        }
    } catch (Exception e) {
        throw new SenderException(e);
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

        method.addHeader(entry.getKey(), entry.getValue());
    }

    //Cmis creates it's own contentType depending on the method and bindingType
    method.setHeader("Content-Type", getContentType());

    log.debug(getLogPrefix() + "HttpSender constructed " + getMethodType() + "-method [" + method.getURI()
            + "] query [" + method.getURI().getQuery() + "] ");
    return method;
}