Package org.apache.http.client.methods

Examples of org.apache.http.client.methods.HttpRequestBase


        }
       
        // redirection should be adjusted with local host header...
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
       
        HttpRequestBase httpRequest = null;
       
        String method = request.getMethod();
       
        if (HttpGet.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpGet(proxyTargetURL);
        }
        else if (HttpHead.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpHead(proxyTargetURL);
        }
        else if (HttpPost.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpPost(proxyTargetURL);
            long contentLength = NumberUtils.toLong(request.getHeader(HTTP.CONTENT_LEN));
           
            if (contentLength > 0L)
            {
                HttpEntity entity = new InputStreamEntity(request.getInputStream(), contentLength);
                ((HttpPost) httpRequest).setEntity(entity);
            }
        }
        else if (HttpPut.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpPut(proxyTargetURL);
           
            long contentLength = NumberUtils.toLong(request.getHeader(HTTP.CONTENT_LEN));
           
            if (contentLength > 0L)
            {
                HttpEntity entity = new InputStreamEntity(request.getInputStream(), contentLength);
                ((HttpPost) httpRequest).setEntity(entity);
            }
        }
        else if (HttpDelete.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpDelete(proxyTargetURL);
        }
        else if (HttpOptions.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpOptions(proxyTargetURL);
        }
        else if (HttpTrace.METHOD_NAME.equals(method))
        {
            httpRequest = new HttpHead(proxyTargetURL);
        }
        else
        {
            throw new HttpReverseProxyException("Unsupported method: " + method);
        }
       
        // set sso credentials if available
        List<SSOSiteCredentials> credsList = getSSOSiteCredentials(proxyTargetURL, httpClient, request);
        if (credsList != null && !credsList.isEmpty())
        {
            SSOSiteCredentials firstCreds = credsList.get(0);
           
            if (firstCreds.isFormAuthentication() && StringUtils.equals(firstCreds.getBaseURL(), proxyTargetURL))
            {
                httpRequest = new HttpPost(proxyTargetURL);
                List <NameValuePair> formParams = new ArrayList<NameValuePair>();
                formParams.add(new BasicNameValuePair(firstCreds.getFormUserField(), firstCreds.getUsername()));
                formParams.add(new BasicNameValuePair(firstCreds.getFormPwdField(), firstCreds.getPassword()));
                ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(formParams));
            }
            else
            {
                for (SSOSiteCredentials creds : credsList)
                {
                    AuthScope authScope = new AuthScope(creds.getHost(), creds.getPort(), creds.getRealm(), creds.getScheme());
                    Credentials usernamePwdCreds = new UsernamePasswordCredentials(creds.getUsername(), creds.getPassword());
                    httpClient.getCredentialsProvider().setCredentials(authScope, usernamePwdCreds);
                }
            }
        }
       
        // pass most headers to proxy target...
        for (Enumeration enumHeaderNames = request.getHeaderNames(); enumHeaderNames.hasMoreElements(); )
        {
            String headerName = (String) enumHeaderNames.nextElement();
           
            if (StringUtils.equalsIgnoreCase(headerName, HTTP.CONTENT_LEN))
                continue;
           
            if (StringUtils.equalsIgnoreCase(headerName, HTTP.TARGET_HOST))
                continue;
           
            for (Enumeration enumHeaderValues = request.getHeaders(headerName); enumHeaderValues.hasMoreElements(); )
            {
                String headerValue = (String) enumHeaderValues.nextElement();
                httpRequest.addHeader(headerName, headerValue);
            }
        }
       
        Map<String, String> defaultRequestHeaders = proxyPathMapper.getDefaultRequestHeaders();
       
        if (defaultRequestHeaders != null)
        {
            for (Map.Entry<String, String> entry : defaultRequestHeaders.entrySet())
            {
                httpRequest.setHeader(entry.getKey(), entry.getValue());
            }
        }
       
        CookieStore cookieStore = httpClient.getCookieStore();
       
        if (cookieStore != null)
        {
            Map<String, String> defaultRequestCookies = proxyPathMapper.getDefaultRequestCookies();
           
            if (defaultRequestCookies != null)
            {
                for (Map.Entry<String, String> entry : defaultRequestCookies.entrySet())
                {
                    cookieStore.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
                }
            }
        }
       
        HttpEntity httpEntity = null;
       
        try
        {
            HttpResponse httpResponse = httpClient.execute(httpRequest);
            httpEntity = httpResponse.getEntity();
           
            String rewriterContextPath = localBaseURL;
           
            if (rewriterContextPath == null)
            {
                rewriterContextPath = request.getContextPath() + request.getServletPath();
            }
           
            int statusCode = httpResponse.getStatusLine().getStatusCode();
           
            // Check if the proxy response is a redirect
            if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */)
            {
                String location = null;
                Header locationHeader = httpResponse.getFirstHeader(HttpReverseProxyConstants.HTTP_HEADER_LOCATION);
               
                if (locationHeader != null)
                {
                    location = locationHeader.getValue();
                }
               
                if (location == null)
                {
                    throw new HttpReverseProxyException("Recieved status code is " + statusCode + " but no " + HttpReverseProxyConstants.HTTP_HEADER_LOCATION + " header was found in the response");
                }
               
                // Modify the redirect to go to this proxy servlet rather that the proxied host
                // FYI, according to rfc2616, "Location" header value must be an absolute URI.
                String localPath = proxyPathMapper.getLocalPath(location);
               
                // if the current proxy path mapper cannot map the remote location to local path, then
                // try to find out a possible path mapper instead one more...
                if (localPath == null)
                {
                    HttpReverseProxyPathMapper proxyPathMapperByLocation = proxyPathMapperProvider.findMapperByRemoteURL(location);
                   
                    if (proxyPathMapperByLocation != null)
                    {
                        localPath = proxyPathMapperByLocation.getLocalPath(location);
                    }
                }
               
                String redirectLocation = null;
               
                if (localPath == null)
                {
                    if (log.isWarnEnabled())
                    {
                        log.warn("Cannot translate the redirect location to local path. {}", location);
                    }
                   
                    redirectLocation = location;
                }
                else
                {
                    redirectLocation = rewriterContextPath + localPath;
                }
               
                if (!responseSetCookies.isEmpty())
                {
                    addResponseCookies(request, response, responseSetCookies, proxyPathMapper, rewriterContextPath);
                }
               
                response.sendRedirect(redirectLocation);
               
                return;
            }
            else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED)
            {
                // 304 needs special handling. See:
                // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
                // We get a 304 whenever passed an 'If-Modified-Since'
                // header and the data on disk has not changed; server
                // responds w/ a 304 saying I'm not going to send the
                // body because the file has not changed.
                response.setIntHeader(HTTP.CONTENT_LEN, 0);
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
               
                if (!responseSetCookies.isEmpty())
                {
                    addResponseCookies(request, response, responseSetCookies, proxyPathMapper, rewriterContextPath);
                }
               
                return;
            }
            else
            {
                // Pass the response code back to the client
                response.setStatus(statusCode);
               
                if (httpEntity != null)
                {
                    boolean rewritable = false;
                    Rewriter rewriter = null;
                    ParserAdaptor parserAdaptor = null;
                   
                    RewriterController rewriterController = proxyPathMapperProvider.getRewriterController(proxyPathMapper);
                   
                    if (rewriterController != null)
                    {
                        parserAdaptor = createParserAdaptor(rewriterController, httpEntity);
                       
                        if (parserAdaptor != null)
                        {
                            rewriter = createRewriter(rewriterController, proxyPathMapper);
                            rewritable = (rewriter != null);
                        }
                    }
                   
                    // Pass response headers back to the client
                    Header [] headerArrayResponse = httpResponse.getAllHeaders();
                   
                    for (Header header : headerArrayResponse)
                    {
                        String headerName = header.getName();
                       
                        if (rewritable && StringUtils.equalsIgnoreCase(headerName, HTTP.CONTENT_LEN))
                            continue;
                       
                        if (StringUtils.startsWithIgnoreCase(headerName, "Set-Cookie"))
                            continue;
                       
                        String headerValue = header.getValue();
                       
                        if (StringUtils.equalsIgnoreCase(headerName, HTTP.TARGET_HOST))
                        {
                            response.setHeader(headerName, hostHeaderValue);
                        }
                        else
                        {
                            response.setHeader(headerName, headerValue);
                        }
                    }
                   
                    if (!responseSetCookies.isEmpty())
                    {
                        addResponseCookies(request, response, responseSetCookies, proxyPathMapper, rewriterContextPath);
                    }
                   
                    // Send the content to the client
                    writeHttpEntityToClient(response, httpEntity, proxyPathMapper, rewriterContextPath, localPathInfo, rewriter, parserAdaptor);
                }
            }
        }
        catch (IOException e)
        {
            if (log.isDebugEnabled())
            {
                log.error("IOException occurred during execution for " + proxyTargetURL, e);
            }
            else
            {
                log.error("IOException occurred during execution for {} {}", proxyTargetURL, e);
            }
           
            httpRequest.abort();
            httpEntity = null;
           
            throw e;
        }
        catch (Exception e)
        {
            if (log.isDebugEnabled())
            {
                log.error("Exception occurred during execution for " + proxyTargetURL, e);
            }
            else
            {
                log.error("Exception occurred during execution for {} {}", proxyTargetURL, e);
            }
           
            httpRequest.abort();
            httpEntity = null;
           
            throw new HttpReverseProxyException(e);
        }
        finally
View Full Code Here


     */
    protected TomcatManagerResponse invoke( String path, File data, long length )
        throws TomcatManagerException, IOException
    {

        HttpRequestBase httpRequestBase = null;
        if ( data == null )
        {
            httpRequestBase = new HttpGet( url + path );
        }
        else
        {
            HttpPut httpPut = new HttpPut( url + path );

            httpPut.setEntity( new RequestEntityImplementation( data, length, url + path, verbose ) );

            httpRequestBase = httpPut;

        }

        if ( userAgent != null )
        {
            httpRequestBase.setHeader( "User-Agent", userAgent );
        }

        HttpResponse response = httpClient.execute( httpRequestBase, localContext );

        int statusCode = response.getStatusLine().getStatusCode();
View Full Code Here

        res.setHTTPMethod(method);
        res.setURL(url);

        HttpClient httpClient = setupClient(url);
       
        HttpRequestBase httpRequest = null;
        try {
            URI uri = url.toURI();
            if (method.equals(HTTPConstants.POST)) {
                httpRequest = new HttpPost(uri);
            } else if (method.equals(HTTPConstants.PUT)) {
View Full Code Here

    public void process(Exchange exchange) throws Exception {
        if (((HttpEndpoint)getEndpoint()).isBridgeEndpoint()) {
            exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        }
        HttpRequestBase httpRequest = createMethod(exchange);
        Message in = exchange.getIn();
        HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

        // propagate headers as HTTP headers
        for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
            String headerValue = in.getHeader(entry.getKey(), String.class);
            if (strategy != null && !strategy.applyFilterToCamelHeaders(entry.getKey(), headerValue, exchange)) {
                httpRequest.addHeader(entry.getKey(), headerValue);
            }
        }
       
        // lets store the result in the output message.
        HttpResponse httpResponse = null;
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Executing http " + httpRequest.getMethod() + " method: " + httpRequest.getURI().toString());
            }
            httpResponse = executeMethod(httpRequest);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Http responseCode: " + responseCode);
View Full Code Here

        if (queryString != null) {
            builder.append('?');
            builder.append(queryString);
        }

        HttpRequestBase httpRequest = methodToUse.createMethod(builder.toString());

        if (methodToUse.isEntityEnclosing()) {
            ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(requestEntity);
            if (requestEntity != null && requestEntity.getContentType() == null) {
                if (LOG.isDebugEnabled()) {
View Full Code Here

        return doReceive(-1);
    }

    protected Exchange doReceive(int timeout) {
        Exchange exchange = endpoint.createExchange();
        HttpRequestBase method = createMethod();

        // set optional timeout in millis
        if (timeout > 0) {
            HttpConnectionParams.setSoTimeout(method.getParams(), timeout);
        }

        HttpEntity responeEntity = null;
        try {
            HttpResponse response = httpClient.execute(method);
View Full Code Here

        res.setHTTPMethod(method);
        res.setURL(url);

        HttpClient httpClient = setupClient(url);
       
        HttpRequestBase httpRequest = null;
        try {
            URI uri = url.toURI();
            if (method.equals(POST)) {
                httpRequest = new HttpPost(uri);
            } else if (method.equals(PUT)) {
View Full Code Here

      throws ActionException, ProcessException {

    String out = "";
    while (a.hasMoreMessages()) {

      HttpRequestBase e = null;
      try {

        HttpAction ha = a.getNextMessage();

        log.debug(path + ha.getRequest());

        if (ha instanceof Get) {
          if (path.length() > 1) {
            e = new HttpGet(path + ha.getRequest());
          } else {
            e = new HttpGet(ha.getRequest());
          }

          e.getParams().setParameter(ClientPNames.DEFAULT_HOST, host);


          // do get
          out = get(e, a, ha);
        } else if (ha instanceof Post) {
          Post p = (Post) ha;

          if (path.length() > 1) {
            e = new HttpPost(path + ha.getRequest());
          } else {
            e = new HttpPost(ha.getRequest());
          }
          e.getParams().setParameter(ClientPNames.DEFAULT_HOST, host);

            MultipartEntity entity = new MultipartEntity();
            for (String key : p.getParams().keySet()) {
              Object content = p.getParams().get(key);
              if (content != null) {
View Full Code Here

        }
       
        LOG.debug(" The uri used by http request is " + builder.toString());
      

        HttpRequestBase httpRequest = methodToUse.createMethod(builder.toString());

        if (methodToUse.isEntityEnclosing()) {
            ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(requestEntity);
            if (requestEntity != null && requestEntity.getContentType() == null) {
                LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
View Full Code Here

            String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
            if (queryString != null) {
                skipRequestHeaders = URISupport.parseQuery(queryString);
            }
        }
        HttpRequestBase httpRequest = createMethod(exchange);
        Message in = exchange.getIn();
        String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
        if (httpProtocolVersion != null) {
            // set the HTTP protocol version
            httpRequest.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpHelper.parserHttpVersion(httpProtocolVersion));
        }
        HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

        // propagate headers as HTTP headers
        for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
            String key = entry.getKey();
            Object headerValue = in.getHeader(key);

            if (headerValue != null) {
                // use an iterator as there can be multiple values. (must not use a delimiter)
                final Iterator it = ObjectHelper.createIterator(headerValue, null);

                // the value to add as request header
                final List<String> values = new ArrayList<String>();

                // if its a multi value then check each value if we can add it and for multi values they
                // should be combined into a single value
                while (it.hasNext()) {
                    String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());

                    // we should not add headers for the parameters in the uri if we bridge the endpoint
                    // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                    if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                        Object skipValue = skipRequestHeaders.get(key);
                        if (ObjectHelper.equal(skipValue, value)) {
                            continue;
                        }
                    }
                    if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                        values.add(value);
                    }
                }

                // add the value(s) as a http request header
                if (values.size() > 0) {
                    // use the default toString of a ArrayList to create in the form [xxx, yyy]
                    // if multi valued, for a single value, then just output the value as is
                    String s =  values.size() > 1 ? values.toString() : values.get(0);
                    httpRequest.addHeader(key, s);
                }
            }
        }

        // lets store the result in the output message.
        HttpResponse httpResponse = null;
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Executing http {} method: {}", httpRequest.getMethod(), httpRequest.getURI().toString());
            }
            httpResponse = executeMethod(httpRequest);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            LOG.debug("Http responseCode: {}", responseCode);
View Full Code Here

TOP

Related Classes of org.apache.http.client.methods.HttpRequestBase

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.