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

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

Introduction

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

Prototype

public void setHeader(String str, String str2) 

Source Link

Usage

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Makes a Http operation./*w w  w .  java 2  s.  c  om*/
 * 
 * This method set a parameters to the request that avoid being waiting 
 * for the server response or once connected, being waiting to receive 
 * the data.
 * 
 * @param method      Method type to execute. @See HTTP_METHOD.
 * @param url         Url of the request.
 * @param jsonData      The body content of the request (JSON). Can be null.
 * @param headers      The headers to include in the request.
 * @return The content of the request if there is one.
 * @throws Exception
 */
public static String net_httpclient_doAction(HTTP_METHOD method, String url, String jsonData,
        Map<String, String> headers) throws ConnectTimeoutException, SocketTimeoutException, Exception {
    String responseData = null;

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // The time it takes to open TCP connection.
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_DEFAULT_TIMEOUT);
    // Timeout when server does not send data.
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
            CONNECTION_DEFAULT_DATA_RECEIVAL_TIMEOUT);
    // Some tuning that is not required for bit tests.
    //httpclient.getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    httpclient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, true);

    HttpRequestBase httpMethod = null;
    switch (method) {
    case POST:
        httpMethod = new HttpPost(url);
        //Add the body to the request.
        StringEntity se = new StringEntity(jsonData);
        ((HttpPost) httpMethod).setEntity(se);
        break;
    case DELETE:
        httpMethod = new HttpDelete(url);
        break;
    case GET:
        httpMethod = new HttpGet(url);
        break;
    }

    //Add the headers to the request.
    if (headers != null) {
        for (String header : headers.keySet()) {
            httpMethod.setHeader(header, headers.get(header));
        }
    }

    HttpResponse response = httpclient.execute(httpMethod);
    if (LOG_ENABLE) {
        Log.d(TAG,
                "HTTP OPERATION: Read from server - Status Code: " + response.getStatusLine().getStatusCode());
        Log.d(TAG, "HTTP OPERATION: Read from server - Status Message: "
                + response.getStatusLine().getReasonPhrase());
    }

    //Get the response body if there is one.
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //responseData = EntityUtils.toString(entity, "UTF-8");

        InputStream instream = entity.getContent();
        responseData = IOUtils.convertStreamToString(instream);

        if (LOG_ENABLE)
            Log.i(TAG, "HTTP OPERATION: Read from server - return: " + responseData);
    }

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new Exception("Http operation " + method.name() + " failed with error code "
                + response.getStatusLine().getStatusCode() + "(" + response.getStatusLine().getReasonPhrase()
                + ")");
    }

    return responseData;
}

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

/**
 * Setup following elements on httpRequest:
 * <ul>//from   w ww. j a v a2 s  .c  om
 * <li>ConnRoutePNames.LOCAL_ADDRESS enabling IP-SPOOFING</li>
 * <li>Socket and connection timeout</li>
 * <li>Redirect handling</li>
 * <li>Keep Alive header or Connection Close</li>
 * <li>Calls setConnectionHeaders to setup headers</li>
 * <li>Calls setConnectionCookie to setup Cookie</li>
 * </ul>
 * 
 * @param url
 *            {@link URL} of the request
 * @param httpRequest
 *            http request for the request
 * @param res
 *            sample result to set cookies on
 * @throws IOException
 *             if hostname/ip to use could not be figured out
 */
protected void setupRequest(URL url, HttpRequestBase httpRequest, HTTPSampleResult res) throws IOException {

    HttpParams requestParams = httpRequest.getParams();

    // Set up the local address if one exists
    final InetAddress inetAddr = getIpSourceAddress();
    if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
        requestParams.setParameter(ConnRoutePNames.LOCAL_ADDRESS, inetAddr);
    } else if (localAddress != null) {
        requestParams.setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);
    } else { // reset in case was set previously
        requestParams.removeParameter(ConnRoutePNames.LOCAL_ADDRESS);
    }

    int rto = getResponseTimeout();
    if (rto > 0) {
        requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, rto);
    }

    int cto = getConnectTimeout();
    if (cto > 0) {
        requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cto);
    }

    requestParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, getAutoRedirects());

    // a well-behaved browser is supposed to send 'Connection: close'
    // with the last request to an HTTP server. Instead, most browsers
    // leave it to the server to close the connection after their
    // timeout period. Leave it to the JMeter user to decide.
    if (getUseKeepAlive()) {
        httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
    } else {
        httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
    }

    setConnectionHeaders(httpRequest, url, getHeaderManager(), getCacheManager());

    String cookies = setConnectionCookie(httpRequest, url, getCookieManager());

    if (res != null) {
        res.setCookies(cookies);
    }

}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the {@link HttpUriRequest} that will be used to {@linkplain #doProxyRequest(Page.Request, Channel.Mode)
 * proxy} content while fulfilling the specified <code>pageRequest</code>. This method will
 * {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) calculate} the proxied file URL,
 * {@linkplain #createProxyRequestObject(Page.Request, Channel.Mode, URL) create} the appropriate type of request
 * object, set it's {@linkplain HttpUriRequest#setHeader(String, String) headers}, and, if this channel is
 * {@linkplain net.www_eee.portal.Page.Request#isMaximized(Channel) maximized}, set any
 * {@linkplain HttpEntityEnclosingRequest#setEntity(HttpEntity) entity} that was
 * {@linkplain net.www_eee.portal.Page.Request#getEntity() provided} by the <code>pageRequest</code>.
 * /* w  w  w .  j a  va 2  s  .co  m*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param proxyClient The {@link #createProxyClient(Page.Request) HttpClient} performing the proxy request.
 * @return The proxy {@link HttpUriRequest} object.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #doProxyRequest(Page.Request, Channel.Mode)
 * @see #PROXY_REQUEST_HOOK
 */
protected HttpRequestBase createProxyRequest(final Page.Request pageRequest, final Mode mode,
        final CloseableHttpClient proxyClient) throws WWWEEEPortal.Exception, WebApplicationException {
    final URL proxiedFileURL = getProxiedFileURL(pageRequest, mode, true);

    final Object[] context = new Object[] { mode, proxiedFileURL };
    HttpRequestBase proxyRequest = PROXY_REQUEST_HOOK.value(plugins, context, pageRequest);
    if (proxyRequest == null) {

        proxyRequest = createProxyRequestObject(pageRequest, mode, proxiedFileURL);

        final String userAgent = getProxyRequestUserAgentHeader(pageRequest, mode, proxyClient, proxiedFileURL,
                proxyRequest);
        if (userAgent != null)
            proxyRequest.setHeader("User-Agent", userAgent);
        final String acceptLanguage = getProxyRequestAcceptLanguageHeader(pageRequest, mode, proxyClient,
                proxiedFileURL, proxyRequest);
        if (acceptLanguage != null)
            proxyRequest.setHeader("Accept-Language", acceptLanguage);
        final String accept = getProxyRequestAcceptHeader(pageRequest, mode, proxyClient, proxiedFileURL,
                proxyRequest);
        if (accept != null)
            proxyRequest.setHeader("Accept", accept);
        final String authorization = getProxyRequestAuthorizationHeader(pageRequest, mode, proxyClient,
                proxiedFileURL, proxyRequest);
        if (authorization != null)
            proxyRequest.setHeader("Authorization", authorization);

        if (Mode.RESOURCE.equals(mode)) {
            final Optional<String> ifMatch = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(),
                    "If-Match", Function.identity());
            if (ifMatch.isPresent())
                proxyRequest.setHeader("If-Match", ifMatch.get());
            final Optional<String> ifModifiedSince = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(),
                    "If-Modified-Since", Function.identity());
            if (ifModifiedSince.isPresent())
                proxyRequest.setHeader("If-Modified-Since", ifModifiedSince.get());
            final Optional<String> ifNoneMatch = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(),
                    "If-None-Match", Function.identity());
            if (ifNoneMatch.isPresent())
                proxyRequest.setHeader("If-None-Match", ifNoneMatch.get());
            final Optional<String> ifUnmodifiedSince = RESTUtil.getFirstHeaderValue(
                    pageRequest.getHttpHeaders(), "If-Unmodified-Since", Function.identity());
            if (ifUnmodifiedSince.isPresent())
                proxyRequest.setHeader("If-Unmodified-Since", ifUnmodifiedSince.get());
        }

        if (!isCacheControlClientDirectivesDisabled(pageRequest)) {
            final Optional<CacheControl> cacheControl = RESTUtil
                    .getFirstHeaderValue(pageRequest.getHttpHeaders(), "Cache-Control", CacheControl::valueOf);
            if (cacheControl.isPresent())
                proxyRequest.setHeader("Cache-Control", cacheControl.get().toString());
        }

        if (pageRequest.isMaximized(this)) {

            final MediaType contentType = pageRequest.getHttpHeaders().getMediaType();
            if (contentType != null)
                proxyRequest.setHeader("Content-Type", contentType.toString());

            final DataSource entity = pageRequest.getEntity();
            if ((entity != null) && (proxyRequest instanceof HttpEntityEnclosingRequest)) {
                try {
                    final Optional<String> contentLengthString = RESTUtil.getFirstHeaderValue(
                            pageRequest.getHttpHeaders(), "Content-Length", Function.identity());
                    final HttpEntity httpEntity = new InputStreamEntity(entity.getInputStream(),
                            (contentLengthString.isPresent()) ? Long.parseLong(contentLengthString.get()) : -1);
                    ((HttpEntityEnclosingRequest) proxyRequest).setEntity(httpEntity);
                } catch (NumberFormatException nfe) {
                    throw new WebApplicationException(nfe, Response.Status.INTERNAL_SERVER_ERROR);
                } catch (IOException ioe) {
                    throw new WWWEEEPortal.OperationalException(ioe);
                }
            }

        } // if (pageRequest.isMaximized(this))

    } // if (proxyRequest == null)
    proxyRequest = PROXY_REQUEST_HOOK
            .requireFilteredResult(PROXY_REQUEST_HOOK.filter(plugins, context, pageRequest, proxyRequest));
    return proxyRequest;
}

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 {/*from  ww w .j  a va  2s  .  c  om*/
        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;
}

From source file:org.georchestra.security.Proxy.java

private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse,
        RequestType requestType, String sURL, boolean localProxy) {
    HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling();

    RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build();
    htb.setDefaultRequestConfig(config);

    ///*from  ww  w.ja  v a 2 s  .  c om*/
    // Handle http proxy for external request.
    // Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128)
    htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    HttpClient httpclient = htb.build();

    HttpResponse proxiedResponse = null;
    int statusCode = 500;

    try {
        URL url = null;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) { // not an url
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }

        // HTTP protocol is required
        if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "HTTP protocol expected. \"" + url.getProtocol() + "\" used.");
            return;
        }

        // check if proxy must filter on final host
        if (!strategyForFilteringRequests.allowRequest(url)) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Host \"" + url.getHost() + "\" is not allowed to be requested");
            return;
        }

        logger.debug("Final request -- " + sURL);

        HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL);
        headerManagement.configureRequestHeaders(request, proxyingRequest);

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Header[] originalHeaders = proxyingRequest.getHeaders("sec-org");
            String org = "";
            for (Header originalHeader : originalHeaders) {
                org = originalHeader.getValue();
            }
            // no OGC SERVICE log if request going through /proxy/?url=
            if (!request.getRequestURI().startsWith("/sec/proxy/")) {
                String[] roles = new String[] { "" };
                try {
                    Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles");
                    if (rolesHeaders.length > 0) {
                        roles = rolesHeaders[0].getValue().split(";");
                    }
                } catch (Exception e) {
                    logger.error("Unable to compute roles");
                }
                statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles));

            }

        } catch (Exception e) {
            logger.error("Unable to log the request into the statistics logger", e);
        }

        if (localProxy) {
            //
            // Hack for geoserver
            // Should not be here. We must use a ProxyTarget class and
            // define
            // if Host header should be forwarded or not.
            //
            request.getHeader("Host");
            proxyingRequest.setHeader("Host", request.getHeader("Host"));

            if (logger.isDebugEnabled()) {
                logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue()
                        + " for proxy request.");
            }
        }
        proxiedResponse = executeHttpRequest(httpclient, proxyingRequest);
        StatusLine statusLine = proxiedResponse.getStatusLine();
        statusCode = statusLine.getStatusCode();
        String reasonPhrase = statusLine.getReasonPhrase();

        if (reasonPhrase != null && statusCode > 399) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase);
            }

            if (statusCode == 401) {
                //
                // Handle case of basic authentication.
                //
                Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate");
                finalResponse.setHeader("WWW-Authenticate",
                        (authHeader == null) ? "Basic realm=\"Authentication required\""
                                : authHeader.getValue());
            }

            // 403 and 404 are handled by specific JSP files provided by the
            // security-proxy webapp
            if ((statusCode == 404) || (statusCode == 403)) {
                finalResponse.sendError(statusCode);
                return;
            }
        }

        headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse,
                this.targets);

        if (statusCode == 302 || statusCode == 301) {
            adjustLocation(request, proxiedResponse, finalResponse);
        }
        // get content type

        String contentType = null;
        if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) {
            contentType = proxiedResponse.getEntity().getContentType().getValue();
            logger.debug("content-type detected: " + contentType);
        }

        // content type has to be valid
        if (isCharsetRequiredForContentType(contentType)) {
            doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType);
        } else {
            logger.debug("charset not required for contentType: " + contentType);
            doHandleRequest(request, finalResponse, requestType, proxiedResponse);
        }
    } catch (IOException e) {
        // connection problem with the host
        logger.error("Exception occured when trying to connect to the remote host: ", e);
        try {
            finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (IOException e2) {
            // error occured while trying to return the
            // "service unavailable status"
            finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.springframework.extensions.webscripts.connector.RemoteClient.java

/**
 * Service a remote URL and write the the result into an output stream.
 * If an InputStream is provided then a POST will be performed with the content
 * pushed to the url. Otherwise a standard GET will be performed.
 * //from   www .j a  va 2 s.c om
 * @param url    The URL to open and retrieve data from
 * @param in     The optional InputStream - if set a POST or similar will be performed
 * @param out    The OutputStream to write result to
 * @param res    Optional HttpServletResponse - to which response headers will be copied - i.e. proxied
 * @param status The status object to apply the response code too
 * 
 * @return encoding specified by the source URL - may be null
 * 
 * @throws IOException
 */
private String service(URL url, InputStream in, OutputStream out, HttpServletRequest req,
        HttpServletResponse res, ResponseStatus status) throws IOException {
    final boolean trace = logger.isTraceEnabled();
    final boolean debug = logger.isDebugEnabled();
    if (debug) {
        logger.debug("Executing " + "(" + requestMethod + ") " + url.toString());
        if (in != null)
            logger.debug(" - InputStream supplied - will push...");
        if (out != null)
            logger.debug(" - OutputStream supplied - will stream response...");
        if (req != null && res != null)
            logger.debug(" - Full Proxy mode between servlet request and response...");
    }

    // aquire and configure the HttpClient
    HttpClient httpClient = createHttpClient(url);

    URL redirectURL = url;
    HttpResponse response;
    HttpRequestBase method = null;
    int retries = 0;
    // Only process redirects if we are not processing a 'push'
    int maxRetries = in == null ? this.maxRedirects : 1;
    try {
        do {
            // Release a previous method that we processed due to a redirect
            if (method != null) {
                method.reset();
                method = null;
            }

            switch (this.requestMethod) {
            default:
            case GET:
                method = new HttpGet(redirectURL.toString());
                break;
            case PUT:
                method = new HttpPut(redirectURL.toString());
                break;
            case POST:
                method = new HttpPost(redirectURL.toString());
                break;
            case DELETE:
                method = new HttpDelete(redirectURL.toString());
                break;
            case HEAD:
                method = new HttpHead(redirectURL.toString());
                break;
            case OPTIONS:
                method = new HttpOptions(redirectURL.toString());
                break;
            }

            // proxy over any headers from the request stream to proxied request
            if (req != null) {
                Enumeration<String> headers = req.getHeaderNames();
                while (headers.hasMoreElements()) {
                    String key = headers.nextElement();
                    if (key != null) {
                        key = key.toLowerCase();
                        if (!this.removeRequestHeaders.contains(key) && !this.requestProperties.containsKey(key)
                                && !this.requestHeaders.containsKey(key)) {
                            method.setHeader(key, req.getHeader(key));
                            if (trace)
                                logger.trace("Proxy request header: " + key + "=" + req.getHeader(key));
                        }
                    }
                }
            }

            // apply request properties, allows for the assignment and override of specific header properties
            // firstly pre-configured headers are applied and overridden/augmented by runtime request properties 
            final Map<String, String> headers = (Map<String, String>) this.requestHeaders.clone();
            headers.putAll(this.requestProperties);
            if (headers.size() != 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String headerName = entry.getKey();
                    String headerValue = headers.get(headerName);
                    if (headerValue != null) {
                        method.setHeader(headerName, headerValue);
                    }
                    if (trace)
                        logger.trace("Set request header: " + headerName + "=" + headerValue);
                }
            }

            // Apply cookies
            if (this.cookies != null && !this.cookies.isEmpty()) {
                StringBuilder builder = new StringBuilder(128);
                for (Map.Entry<String, String> entry : this.cookies.entrySet()) {
                    if (builder.length() != 0) {
                        builder.append(';');
                    }
                    builder.append(entry.getKey());
                    builder.append('=');
                    builder.append(entry.getValue());
                }

                String cookieString = builder.toString();

                if (debug)
                    logger.debug("Setting Cookie header: " + cookieString);
                method.setHeader(HEADER_COOKIE, cookieString);
            }

            // HTTP basic auth support
            if (this.username != null && this.password != null) {
                String auth = this.username + ':' + this.password;
                method.addHeader("Authorization",
                        "Basic " + Base64.encodeBytes(auth.getBytes(), Base64.DONT_BREAK_LINES));
                if (debug)
                    logger.debug("Applied HTTP Basic Authorization for user: " + this.username);
            }

            // prepare the POST/PUT entity data if input supplied
            if (in != null) {
                method.setHeader(HEADER_CONTENT_TYPE, getRequestContentType());
                if (debug)
                    logger.debug("Set Content-Type=" + getRequestContentType());

                boolean urlencoded = getRequestContentType().startsWith(X_WWW_FORM_URLENCODED);
                if (!urlencoded) {
                    // apply content-length here if known (i.e. from proxied req)
                    // if this is not set, then the content will be buffered in memory
                    long contentLength = -1L;
                    if (req != null) {
                        String contentLengthStr = req.getHeader(HEADER_CONTENT_LENGTH);
                        if (contentLengthStr != null) {
                            try {
                                long actualContentLength = Long.parseLong(contentLengthStr);
                                if (actualContentLength > 0) {
                                    contentLength = actualContentLength;
                                }
                            } catch (NumberFormatException e) {
                                logger.warn("Can't parse 'Content-Length' header from '" + contentLengthStr
                                        + "'. The contentLength is set to -1");
                            }
                        }
                    }

                    if (debug)
                        logger.debug(requestMethod + " entity Content-Length=" + contentLength);

                    // remove the Content-Length header as the setEntity() method will perform this explicitly
                    method.removeHeaders(HEADER_CONTENT_LENGTH);

                    try {
                        // Apache doc for AbstractHttpEntity states:
                        // HttpClient must use chunk coding if the entity content length is unknown (== -1).
                        HttpEntity entity = new InputStreamEntity(in, contentLength);
                        ((HttpEntityEnclosingRequest) method)
                                .setEntity(contentLength == -1L || contentLength > 16384L ? entity
                                        : new BufferedHttpEntity(entity));
                        ((HttpEntityEnclosingRequest) method).setHeader(HTTP.EXPECT_DIRECTIVE,
                                HTTP.EXPECT_CONTINUE);
                    } catch (IOException e) {
                        // During the creation of the BufferedHttpEntity the underlying stream can be closed by the client,
                        // this happens if the request is discarded by the browser - we don't log this IOException as INFO
                        // as that would fill the logs with unhelpful noise - enable DEBUG logging to see these messages.
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    if (req != null) {
                        // apply any supplied request parameters
                        Map<String, String[]> postParams = req.getParameterMap();
                        if (postParams != null) {
                            List<NameValuePair> params = new ArrayList<NameValuePair>(postParams.size());
                            for (String key : postParams.keySet()) {
                                String[] values = postParams.get(key);
                                for (int i = 0; i < values.length; i++) {
                                    params.add(new BasicNameValuePair(key, values[i]));
                                }
                            }
                        }
                        // ensure that the Content-Length header is not directly proxied - as the underlying
                        // HttpClient will encode the body as appropriate - cannot assume same as the original client sent
                        method.removeHeaders(HEADER_CONTENT_LENGTH);
                    } else {
                        // Apache doc for AbstractHttpEntity states:
                        // HttpClient must use chunk coding if the entity content length is unknown (== -1).
                        HttpEntity entity = new InputStreamEntity(in, -1L);
                        ((HttpEntityEnclosingRequest) method).setEntity(entity);
                        ((HttpEntityEnclosingRequest) method).setHeader(HTTP.EXPECT_DIRECTIVE,
                                HTTP.EXPECT_CONTINUE);
                    }
                }
            }

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Execute the method to get the response
            response = httpClient.execute(method);

            redirectURL = processResponse(redirectURL, response);
        } while (redirectURL != null && ++retries < maxRetries);

        // record the status code for the internal response object
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR && this.exceptionOnError) {
            buildProxiedServerError(response);
        } else if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            // Occurs when server is down and likely an ELB response 
            throw new ConnectException(response.toString());
        }
        boolean allowResponseCommit = (responseCode != HttpServletResponse.SC_UNAUTHORIZED
                || commitResponseOnAuthenticationError);
        status.setCode(responseCode);
        if (debug)
            logger.debug("Response status code: " + responseCode);

        // walk over headers that are returned from the connection
        // if we have a servlet response, push the headers back to the existing response object
        // otherwise, store headers on status
        Header contentType = null;
        Header contentLength = null;
        for (Header header : response.getAllHeaders()) {
            // NOTE: Tomcat does not appear to be obeying the servlet spec here.
            //       If you call setHeader() the spec says it will "clear existing values" - i.e. not
            //       add additional values to existing headers - but for Server and Transfer-Encoding
            //       if we set them, then two values are received in the response...
            // In addition handle the fact that the key can be null.
            final String key = header.getName();
            if (key != null) {
                if (!key.equalsIgnoreCase(HEADER_SERVER) && !key.equalsIgnoreCase(HEADER_TRANSFER_ENCODING)) {
                    if (res != null && allowResponseCommit
                            && !this.removeResponseHeaders.contains(key.toLowerCase())) {
                        res.setHeader(key, header.getValue());
                    }

                    // store headers back onto status
                    status.setHeader(key, header.getValue());

                    if (trace)
                        logger.trace("Response header: " + key + "=" + header.getValue());
                }

                // grab a reference to the the content-type header here if we find it
                if (contentType == null && key.equalsIgnoreCase(HEADER_CONTENT_TYPE)) {
                    contentType = header;
                    // additional optional processing based on the Content-Type header
                    processContentType(url, res, contentType);
                }
                // grab a reference to the Content-Length header here if we find it
                else if (contentLength == null && key.equalsIgnoreCase(HEADER_CONTENT_LENGTH)) {
                    contentLength = header;
                }
            }
        }

        // locate response encoding from the headers
        String encoding = null;
        String ct = null;
        if (contentType != null) {
            ct = contentType.getValue();
            int csi = ct.indexOf(CHARSETEQUALS);
            if (csi != -1) {
                encoding = ct.substring(csi + CHARSETEQUALS.length());
                if ((csi = encoding.lastIndexOf(';')) != -1) {
                    encoding = encoding.substring(0, csi);
                }
                if (debug)
                    logger.debug("Response charset: " + encoding);
            }
        }
        if (debug)
            logger.debug("Response encoding: " + contentType);

        // generate container driven error message response for specific response codes
        if (res != null && responseCode == HttpServletResponse.SC_UNAUTHORIZED && allowResponseCommit) {
            res.sendError(responseCode, response.getStatusLine().getReasonPhrase());
        } else {
            // push status to existing response object if required
            if (res != null && allowResponseCommit) {
                res.setStatus(responseCode);
            }
            // perform the stream write from the response to the output
            int bufferSize = this.bufferSize;
            if (contentLength != null) {
                long length = Long.parseLong(contentLength.getValue());
                if (length < bufferSize) {
                    bufferSize = (int) length;
                }
            }
            copyResponseStreamOutput(url, res, out, response, ct, bufferSize);
        }

        // if we get here call was successful
        return encoding;
    } catch (ConnectTimeoutException | SocketTimeoutException timeErr) {
        // caught a socket timeout IO exception - apply internal error code
        logger.info("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_REQUEST_TIMEOUT);
        status.setException(timeErr);
        status.setMessage(timeErr.getMessage());
        if (res != null) {
            //return a Request Timeout error
            res.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT, timeErr.getMessage());
        }

        throw timeErr;
    } catch (UnknownHostException | ConnectException hostErr) {
        // caught an unknown host IO exception 
        logger.info("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        status.setException(hostErr);
        status.setMessage(hostErr.getMessage());
        if (res != null) {
            // return server error code
            res.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE, hostErr.getMessage());
        }

        throw hostErr;
    } catch (IOException ioErr) {
        // caught a general IO exception - apply generic error code so one gets returned
        logger.info("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        status.setException(ioErr);
        status.setMessage(ioErr.getMessage());
        if (res != null) {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ioErr.getMessage());
        }

        throw ioErr;
    } catch (RuntimeException e) {
        // caught an exception - apply generic error code so one gets returned
        logger.debug("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        status.setException(e);
        status.setMessage(e.getMessage());
        if (res != null) {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }

        throw e;
    } finally {
        // reset state values
        if (method != null) {
            method.releaseConnection();
        }
        setRequestContentType(null);
        this.requestMethod = HttpMethod.GET;
    }
}

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

public void addCustomHeaders(HttpRequestBase 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 BasicHeader(nv.getName(), nv.getValue());
                    if (HTTPConstants.HEADER_USER_AGENT.equals(header.getName())) {
                        isCustomUserAgentSet = true;
                    }/* www.  ja  va2  s  . c o  m*/
                    method.addHeader(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.addHeader(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.getAllHeaders();

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

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

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

}

From source file:de.betterform.connector.http.AbstractHTTPConnector.java

protected void execute(HttpRequestBase httpRequestBase) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    //HttpClient client = new HttpClient();
    HttpParams httpParams = new BasicHttpParams();

    DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams);

    if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("SSL_CUSTOM_SCHEME");
        LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: "
                + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT));
        String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT);
        if (contextPath != null) {
            initSSLScheme(contextPath);/*  w w w .  j  a v  a 2  s.  c  o m*/
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context params>>>");
        Map map = getContext();
        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            Object value = map.get(key);
            if (value != null)
                LOGGER.debug(key + "=" + value.toString());
        }
        LOGGER.debug("<<<end params");
    }
    String username = null;
    String password = null;
    String realm = null;

    //add custom header to signal XFormsFilter to not process this internal request
    //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true");
    httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true");

    /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders
    if (getContext().containsKey(HTTP_REQUEST_HEADERS)) {
        RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS);

        // Iterator it =
        Map headersToAdd = new HashMap();
        for (RequestHeader header : httpRequestHeaders.getAllHeaders()) {
            String headername = header.getName();
            String headervalue = header.getValue();

            if (headername.equals("username")) {
                username = headervalue;
            } else if (headername.equals("password")) {
                password = headervalue;
            } else if (headername.equals("realm")) {
                realm = headervalue;
            } else {
                if (headersToAdd.containsKey(headername)) {
                    String formerValue = (String) headersToAdd.get(headername);
                    headersToAdd.put(headername, formerValue + "," + headervalue);
                } else {
                    if (headername.equals("accept-encoding")) {
                        // do nothing
                        LOGGER.debug("do not add accept-encoding:" + headervalue + " for request");
                    } else {
                        headersToAdd.put(headername, headervalue);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("setting header: " + headername + " value: " + headervalue);
                        }
                    }
                }
            }
        }
        Iterator keyIterator = headersToAdd.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = (String) keyIterator.next();
            //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key)));
            httpRequestBase.setHeader(key, (String) headersToAdd.get(key));
            //httpRequestBase.addHeader(key, (String) headersToAdd.get(key));
        }
    }
    if (httpRequestBase.containsHeader("Content-Length")) {
        //remove content-length if present httpclient will recalucalte the value.
        httpRequestBase.removeHeaders("Content-Length");
    }
    if (username != null && password != null) {
        URI targetURI = null;
        //targetURI = httpMethod.getURI();
        targetURI = httpRequestBase.getURI();
        //client.getParams().setAuthenticationPreemptive(true);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        if (realm == null) {
            realm = AuthScope.ANY_REALM;
        }
        //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        client.getCredentialsProvider()
                .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();

        authCache.put(new HttpHost(targetURI.getHost()), basicAuth);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        //Needed? httpMethod.setDoAuthentication(true);

    }
    //alternative method for non-tomcat servers
    if (getContext().containsKey(REQUEST_COOKIE)) {
        //HttpState state = client.getState();
        HttpParams state = client.getParams();

        //state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
        state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) {
            Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE);
            if (cookiesIn[0] != null) {
                for (int i = 0; i < cookiesIn.length; i++) {
                    Cookie cookie = cookiesIn[i];
                    //state.addCookie(cookie);
                    client.getCookieStore().addCookie(cookie);
                }
                /*
                  Cookie[] cookies = state.getCookies();
                        
                Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies);
                httpMethod.setRequestHeader(cookieOut);
                client.setState(state);
                  */
                List<Cookie> cookies = client.getCookieStore().getCookies();
                List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies);
                Header[] headers = cookieHeaders.toArray(new Header[0]);

                for (int i = 0; i < headers.length; i++) {
                    httpRequestBase.addHeader(headers[i]);
                }

                client.setParams(state);
            }
        } else {
            throw new MalformedCookieException(
                    "Cookies must be passed as org.apache.commons.httpclient.Cookie objects.");
        }
    }

    if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("Using customSSL-Protocol-Handler");
        Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME))
                .iterator();

        while (schemes.hasNext()) {
            client.getConnectionManager().getSchemeRegistry().register(schemes.next());
        }
    }

    if (httpRequestBase.getURI().isAbsolute()) {
        httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost());
    }

    HttpResponse httpResponse = client.execute(httpRequestBase);
    statusCode = httpResponse.getStatusLine().getStatusCode();
    reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    try {
        if (statusCode >= 300) {
            // Allow 302 only
            if (statusCode != 302) {
                throw new XFormsInternalSubmitException(statusCode, reasonPhrase,
                        EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
            }
        }
        this.handleHttpMethod(httpResponse);
    } catch (Exception e) {

        LOGGER.trace("AbstractHTTPConnector Exception: ", e);
        try {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(),
                    EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
        } catch (IOException e1) {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR);
        }
    }

}