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

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

Introduction

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

Prototype

public URI getURI() 

Source Link

Document

Returns the original request URI.

Usage

From source file:org.dasein.cloud.atmos.AtmosMethod.java

protected void authorize(@Nonnull ProviderContext ctx, @Nonnull HttpRequestBase method,
        @Nonnull String contentType, @Nullable String range) throws CloudException, InternalException {
    ArrayList<Header> emcHeaders = new ArrayList<Header>();
    String date = provider.formatTime(System.currentTimeMillis());

    try {// ww  w  .  j a v  a 2s.c om
        method.addHeader("x-emc-uid",
                new String(ctx.getAccessPublic(), "utf-8") + "/" + ctx.getAccountNumber());
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 error: " + e.getMessage());
        throw new InternalException(e);
    }
    method.addHeader("Date", date);

    for (Header h : method.getAllHeaders()) {
        if (h.getName().toLowerCase().startsWith("x-emc")) {
            emcHeaders.add(h);
        }
    }
    String signatureString = toSignatureString(method, contentType, range == null ? "" : range, date,
            method.getURI(), emcHeaders);
    logger.debug(signatureString);
    String signature = sign(ctx, signatureString);
    logger.debug(signature);
    method.addHeader("x-emc-signature", signature);
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) {
    if (depth >= MAX_REDIRECT) {
        throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached");
    }/*  w  w w.j  a  va  2s .c  om*/

    RequestCallback callback = req.getRequestCallback();

    HttpRequestBase method = req.getMethod();
    String verificationText = req.getVerificationText();
    String url = method.getURI().toString();

    // save the browser and version if it's not yet been set
    if (har != null && har.getLog().getBrowser() == null) {
        Header[] uaHeaders = method.getHeaders("User-Agent");
        if (uaHeaders != null && uaHeaders.length > 0) {
            String userAgent = uaHeaders[0].getValue();
            try {
                // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0'
                ReadableUserAgent uai = PARSER.parse(userAgent);
                String browser = uai.getName();
                String version = uai.getVersionNumber().toVersionString();
                har.getLog().setBrowser(new HarNameVersion(browser, version));
            } catch (Exception e) {
                LOG.warn("Failed to parse user agent string", e);
            }
        }
    }

    // process any rewrite requests
    boolean rewrote = false;
    String newUrl = url;
    for (RewriteRule rule : rewriteRules) {
        Matcher matcher = rule.match.matcher(newUrl);
        newUrl = matcher.replaceAll(rule.replace);
        rewrote = true;
    }

    if (rewrote) {
        try {
            method.setURI(new URI(newUrl));
            url = newUrl;
        } catch (URISyntaxException e) {
            LOG.warn("Could not rewrite url to %s", newUrl);
        }
    }

    // handle whitelist and blacklist entries
    int mockResponseCode = -1;
    synchronized (this) {
        // guard against concurrent modification of whitelistEntry
        if (whitelistEntry != null) {
            boolean found = false;
            for (Pattern pattern : whitelistEntry.patterns) {
                if (pattern.matcher(url).matches()) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                mockResponseCode = whitelistEntry.responseCode;
            }
        }
    }

    if (blacklistEntries != null) {
        for (BlacklistEntry blacklistEntry : blacklistEntries) {
            if (blacklistEntry.pattern.matcher(url).matches()) {
                mockResponseCode = blacklistEntry.responseCode;
                break;
            }
        }
    }

    if (!additionalHeaders.isEmpty()) {
        // Set the additional headers
        for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            method.removeHeaders(key);
            method.addHeader(key, value);
        }
    }

    String charSet = "UTF-8";
    String responseBody = null;

    InputStream is = null;
    int statusCode = -998;
    long bytes = 0;
    boolean gzipping = false;
    boolean contentMatched = true;
    OutputStream os = req.getOutputStream();
    if (os == null) {
        os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB
    }
    if (verificationText != null) {
        contentMatched = false;
    }

    // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down)
    // we still have the attempt associated, even if we never got a response
    HarEntry entry = new HarEntry(harPageRef);

    // clear out any connection-related information so that it's not stale from previous use of this thread.
    RequestInfo.clear(url, entry);

    entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol()));
    entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol()));
    if (this.har != null && harPageRef != null) {
        har.getLog().addEntry(entry);
    }

    String query = method.getURI().getRawQuery();
    if (query != null) {
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(query, params, "UTF-8");
        for (String k : params.keySet()) {
            for (Object v : params.getValues(k)) {
                entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v));
            }
        }
    }

    String errorMessage = null;
    HttpResponse response = null;

    BasicHttpContext ctx = new BasicHttpContext();

    ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime());
    synchronized (activeRequests) {
        activeRequests.add(activeRequest);
    }

    // for dealing with automatic authentication
    if (authType == AuthType.NTLM) {
        // todo: not supported yet
        //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine()));
    } else if (authType == AuthType.BASIC) {
        ctx.setAttribute("preemptive-auth", new BasicScheme());
    }

    StatusLine statusLine = null;
    try {
        // set the User-Agent if it's not already set
        if (method.getHeaders("User-Agent").length == 0) {
            method.addHeader("User-Agent", "BrowserMob VU/1.0");
        }

        // was the request mocked out?
        if (mockResponseCode != -1) {
            statusCode = mockResponseCode;

            // TODO: HACKY!!
            callback.handleHeaders(new Header[] { new Header() {
                @Override
                public String getName() {
                    return "Content-Type";
                }

                @Override
                public String getValue() {
                    return "text/plain";
                }

                @Override
                public HeaderElement[] getElements() throws ParseException {
                    return new HeaderElement[0];
                }
            } });
            // Make sure we set the status line here too.
            // Use the version number from the request
            ProtocolVersion version = null;
            int reqDotVersion = req.getProxyRequest().getDotVersion();
            if (reqDotVersion == -1) {
                version = new HttpVersion(0, 9);
            } else if (reqDotVersion == 0) {
                version = new HttpVersion(1, 0);
            } else if (reqDotVersion == 1) {
                version = new HttpVersion(1, 1);
            }
            // and if not any of these, trust that a Null version will
            // cause an appropriate error
            callback.handleStatusLine(
                    new BasicStatusLine(version, statusCode, "Status set by browsermob-proxy"));
            // No mechanism to look up the response text by status code,
            // so include a notification that this is a synthetic error code.
        } else {
            response = httpClient.execute(method, ctx);
            statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            if (callback != null) {
                callback.handleStatusLine(statusLine);
                callback.handleHeaders(response.getAllHeaders());
            }

            if (response.getEntity() != null) {
                is = response.getEntity().getContent();
            }

            // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204)
            if (is != null) {
                Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");
                if (contentEncodingHeader != null
                        && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
                    gzipping = true;
                }

                // deal with GZIP content!
                if (decompress && gzipping) {
                    is = new GZIPInputStream(is);
                }

                if (captureContent) {
                    // todo - something here?
                    os = new ClonedOutputStream(os);
                }

                bytes = copyWithStats(is, os);
            }
        }
    } catch (Exception e) {
        errorMessage = e.toString();

        if (callback != null) {
            callback.reportError(e);
        }

        // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored)
        if (!shutdown) {
            LOG.info(String.format("%s when requesting %s", errorMessage, url));
        }
    } finally {
        // the request is done, get it out of here
        synchronized (activeRequests) {
            activeRequests.remove(activeRequest);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // this is OK to ignore
            }
        }
    }

    // record the response as ended
    RequestInfo.get().finish();

    // set the start time and other timings
    entry.setStartedDateTime(RequestInfo.get().getStart());
    entry.setTimings(RequestInfo.get().getTimings());
    entry.setServerIPAddress(RequestInfo.get().getResolvedAddress());
    entry.setTime(RequestInfo.get().getTotalTime());

    // todo: where you store this in HAR?
    // obj.setErrorMessage(errorMessage);
    entry.getResponse().setBodySize(bytes);
    entry.getResponse().getContent().setSize(bytes);
    entry.getResponse().setStatus(statusCode);
    if (statusLine != null) {
        entry.getResponse().setStatusText(statusLine.getReasonPhrase());
    }

    boolean urlEncoded = false;
    if (captureHeaders || captureContent) {
        for (Header header : method.getAllHeaders()) {
            if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) {
                urlEncoded = true;
            }

            entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
        }

        if (response != null) {
            for (Header header : response.getAllHeaders()) {
                entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
            }
        }
    }

    if (captureContent) {
        // can we understand the POST data at all?
        if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) {
            HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method;
            HttpEntity entity = enclosingReq.getEntity();

            HarPostData data = new HarPostData();
            data.setMimeType(req.getMethod().getFirstHeader("Content-Type").getValue());
            entry.getRequest().setPostData(data);

            if (urlEncoded || URLEncodedUtils.isEncoded(entity)) {
                try {
                    final String content = new String(req.getCopy().toByteArray(), "UTF-8");
                    if (content != null && content.length() > 0) {
                        List<NameValuePair> result = new ArrayList<NameValuePair>();
                        URLEncodedUtils.parse(result, new Scanner(content), null);

                        ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>();
                        data.setParams(params);

                        for (NameValuePair pair : result) {
                            params.add(new HarPostDataParam(pair.getName(), pair.getValue()));
                        }
                    }
                } catch (Exception e) {
                    LOG.info("Unexpected problem when parsing input copy", e);
                }
            } else {
                // not URL encoded, so let's grab the body of the POST and capture that
                data.setText(new String(req.getCopy().toByteArray()));
            }
        }
    }

    //capture request cookies
    javax.servlet.http.Cookie[] cookies = req.getProxyRequest().getCookies();
    for (javax.servlet.http.Cookie cookie : cookies) {
        HarCookie hc = new HarCookie();
        hc.setName(cookie.getName());
        hc.setValue(cookie.getValue());
        entry.getRequest().getCookies().add(hc);
    }

    String contentType = null;

    if (response != null) {
        try {
            Header contentTypeHdr = response.getFirstHeader("Content-Type");
            if (contentTypeHdr != null) {
                contentType = contentTypeHdr.getValue();
                entry.getResponse().getContent().setMimeType(contentType);

                if (captureContent && os != null && os instanceof ClonedOutputStream) {
                    ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput();

                    if (gzipping) {
                        // ok, we need to decompress it before we can put it in the har file
                        try {
                            InputStream temp = new GZIPInputStream(
                                    new ByteArrayInputStream(copy.toByteArray()));
                            copy = new ByteArrayOutputStream();
                            IOUtils.copy(temp, copy);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if (hasTextualContent(contentType)) {
                        setTextOfEntry(entry, copy, contentType);
                    } else if (captureBinaryContent) {
                        setBinaryContentOfEntry(entry, copy);
                    }
                }

                NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset");

                if (nvp != null) {
                    charSet = nvp.getValue();
                }
            }

            if (os instanceof ByteArrayOutputStream) {
                responseBody = ((ByteArrayOutputStream) os).toString(charSet);

                if (verificationText != null) {
                    contentMatched = responseBody.contains(verificationText);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    if (contentType != null) {
        entry.getResponse().getContent().setMimeType(contentType);
    }

    // checking to see if the client is being redirected
    boolean isRedirect = false;

    String location = null;
    if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) {
        isRedirect = true;

        // pulling the header for the redirect
        Header locationHeader = response.getLastHeader("location");
        if (locationHeader != null) {
            location = locationHeader.getValue();
        } else if (this.followRedirects) {
            throw new RuntimeException("Invalid redirect - missing location header");
        }
    }

    //
    // Response validation - they only work if we're not following redirects
    //

    int expectedStatusCode = req.getExpectedStatusCode();

    // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem
    if (mockResponseCode == -1 && expectedStatusCode > -1) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }
        if (expectedStatusCode != statusCode) {
            if (isRedirect) {
                throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw "
                        + statusCode + " redirecting to: " + location);
            } else {
                throw new RuntimeException(
                        "Expected status code of " + expectedStatusCode + " but saw " + statusCode);
            }
        }
    }

    // Location header check:
    if (isRedirect && (req.getExpectedLocation() != null)) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }

        if (location.compareTo(req.getExpectedLocation()) != 0) {
            throw new RuntimeException(
                    "Expected a redirect to  " + req.getExpectedLocation() + " but saw " + location);
        }
    }

    // end of validation logic

    // basic tail recursion for redirect handling
    if (isRedirect && this.followRedirects) {
        // updating location:
        try {
            URI redirectUri = new URI(location);
            URI newUri = method.getURI().resolve(redirectUri);
            method.setURI(newUri);

            return execute(req, ++depth);
        } catch (URISyntaxException e) {
            LOG.warn("Could not parse URL", e);
        }
    }

    return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage,
            responseBody, contentType, charSet);
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

private HttpResponse getOrDelete(HttpClient client, HttpRequestBase method, boolean authenticate,
        boolean validate) throws Exception {

    LOGGER.debug(method.getURI().toString());

    if (!(method instanceof HttpGet || method instanceof HttpDelete)) {
        throw new IllegalArgumentException("method must be one of GET or DELETE.");
    }//from w  w w  .j  a  v a2 s  .  c om
    HttpResponse response = client.execute(method);

    if (response.getStatusLine().getStatusCode() == SC_MOVED_TEMPORARILY) {
        String redir = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
        if (!method.getURI().toString().equals(redir)) {
            method.setURI(getURI(redir));
            response = getOrDelete(client, method, authenticate, validate);
        }
    }

    if (validate) {
        validateResponse(method.getURI(), response);
    }

    return response;
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

private String doRequest(HttpRequestBase httppost) throws IOException, InterruptedException {
    try (CloseableHttpResponse response = executeMethod(httppost)) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            EntityUtils.consume(response.getEntity());
            // 204, no content
            return "";
        }/*from  www  . j  ava 2s  .c o m*/
        String content = getResponseContent(response);
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw new BitbucketRequestException(response.getStatusLine().getStatusCode(),
                    "HTTP request error. Status: " + response.getStatusLine().getStatusCode() + ": "
                            + response.getStatusLine().getReasonPhrase() + ".\n" + response);
        }
        return content;
    } catch (BitbucketRequestException e) {
        throw e;
    } catch (IOException e) {
        try {
            throw new IOException("Communication error for url: " + httppost.getURI(), e);
        } catch (IOException e1) {
            throw new IOException("Communication error", e);
        }
    } finally {
        release(httppost);
    }
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * /*from   w w  w.ja va 2 s  . c o m*/
 * @param request
 * @param cookie
 * @return The response of the request.
 * @throws WebserverSystemException
 */
private HttpResponse executeRequest(final DefaultHttpClient client, final HttpRequestBase request,
        final URL url, final Cookie cookie, final String username, final String password)
        throws WebserverSystemException {
    try {
        request.setURI(url.toURI());

        if (cookie != null) {
            HttpClientParams.setCookiePolicy(request.getParams(), CookiePolicy.BEST_MATCH);
            request.setHeader("Cookie", cookie.getName() + '=' + cookie.getValue());
        }

        final DefaultHttpClient clientToUse = client == null ? getHttpClient() : client;

        if (PROXY_HOST != null && isProxyRequired(url)) {
            clientToUse.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, PROXY_HOST);
        }

        if (username != null && password != null) {
            setAuthentication(clientToUse, url, username, password);
        }

        final HttpResponse httpResponse = clientToUse.execute(request);

        final int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode / HTTP_RESPONSE_CLASS != HttpServletResponse.SC_OK / HTTP_RESPONSE_CLASS) {
            final String errorPage = readResponse(httpResponse);
            throw new WebserverSystemException(
                    "HTTP connection to \"" + request.getURI().toString() + "\" failed: " + errorPage);
        }

        return httpResponse;
    } catch (final IOException e) {
        throw new WebserverSystemException(e);
    } catch (final URISyntaxException e) {
        throw new WebserverSystemException("Illegal URL '" + url + "'.", e);
    }
}

From source file:com.ibm.sbt.services.client.ClientService.java

/**
 * Execute the specified the request.//from ww  w. j a  va  2s.c  om
 * 
 * @param httpClient
 * @param httpRequestBase
 * @param args
 * @return
 * @throws ClientServicesException
 */
protected HttpResponse executeRequest(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args)
        throws ClientServicesException {
    try {
        return httpClient.execute(httpRequestBase);
    } catch (Exception ex) {
        if (logger.isLoggable(Level.FINE)) {
            String msg = "Exception ocurred while executing request {0} {1}";
            msg = StringUtil.format(msg, httpRequestBase.getMethod(), args);
            logger.log(Level.FINE, msg, ex);
        }

        if (ex instanceof ClientServicesException) {
            throw (ClientServicesException) ex;
        }
        String msg = "Error while executing the REST service {0}";
        String param = httpRequestBase.getURI().toString();
        throw new ClientServicesException(ex, msg, param);
    }
}

From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java

private HttpResponse execute(HttpRequestBase requestBase) throws IOException, OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException {

    applyHeadersCommonToAllRequests(requestBase);

    byte[] responseBody;
    StatusLine statusLine = null;/* w  w  w. j  a va  2s  .  co m*/
    if (LOG.isInfoEnabled()) {
        LOG.startTimer(TIMER_NAME);
    }

    activeCount.incrementAndGet();
    CloseableHttpResponse response = null;
    try {
        response = client.execute(requestBase);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = response.getEntity().getContent();
        if (responseBodyAsStream != null) {
            IOUtils.copy(responseBodyAsStream, outputStream);
        }

        responseBody = outputStream.toByteArray();
        statusLine = response.getStatusLine();
        return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);

    } finally {
        if (response != null) {
            HttpClientUtils.closeQuietly(response);
        }
        requestBase.reset();
        activeCount.decrementAndGet();
        if (LOG.isInfoEnabled()) {
            long elapsedTime = LOG.stopTimer(TIMER_NAME);
            StringBuilder httpInfo = new StringBuilder();
            if (statusLine != null) {
                httpInfo.append("Outbound ").append(statusLine.getProtocolVersion()).append(" Status ")
                        .append(statusLine.getStatusCode());
            } else {
                httpInfo.append("Exception sending request");
            }
            httpInfo.append(" in ").append(elapsedTime).append(" ms ").append(requestBase.getMethod())
                    .append(" ").append(client).append(requestBase.getURI());
            LOG.debug(httpInfo.toString());
        }
    }
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

private SS3Object getObjectWithSignedUrlImpl(String signedGetOrHeadUrl, boolean headOnly)
        throws ServiceException {
    String s3Endpoint = this.getEndpoint();

    HttpRequestBase httpMethod = null;
    if (headOnly) {
        httpMethod = new HttpHead(signedGetOrHeadUrl);
    } else {//  w  ww. ja  v a  2 s  .  c  om
        httpMethod = new HttpGet(signedGetOrHeadUrl);
    }

    HttpResponse httpResponse = performRequest(httpMethod, new int[] { 200 });

    Map<String, Object> map = new HashMap<String, Object>();
    map.putAll(convertHeadersToMap(httpResponse.getAllHeaders()));

    SS3Object responseObject = null;
    try {
        responseObject = ServiceUtils.buildObjectFromUrl(httpMethod.getURI().getHost(),
                httpMethod.getURI().getRawPath().substring(1), s3Endpoint);
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException("Unable to determine name of object created with signed PUT", e);
    }

    responseObject.replaceAllMetadata(
            ServiceUtils.cleanRestMetadataMap(map, this.getRestHeaderPrefix(), this.getRestMetadataPrefix()));
    responseObject.setMetadataComplete(true); // Flag this object as having the complete metadata set.
    if (!headOnly) {
        HttpMethodReleaseInputStream releaseIS = new HttpMethodReleaseInputStream(httpResponse);
        responseObject.setDataInputStream(releaseIS);
    } else {
        // Release connection after HEAD (there's no response content)
        if (log.isDebugEnabled()) {
            log.debug("Releasing HttpMethod after HEAD");
        }
        releaseConnection(httpResponse);
    }

    return responseObject;
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected boolean prepareForwardingCookies(HttpRequestBase method, HttpServletRequest request,
        DefaultHttpClient httpClient) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    Cookie[] cookies = request.getCookies();
    BasicCookieStore cs = new BasicCookieStore();
    httpClient.setCookieStore(cs);/*from  w w w.j  a  v  a  2  s .c om*/
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie != null) {
                String cookiename = cookie.getName();
                if (StringUtil.isNotEmpty(cookiename)) {
                    String cookieval = cookie.getValue();
                    if (cookiename.startsWith(PASSTHRUID)) {
                        cookiename = cookiename.substring(PASSTHRUID.length());
                        if (isCookieAllowed(cookiename)) {
                            String[] parts = decodeCookieNameAndPath(cookiename);
                            if (parts != null && parts.length == 3) {
                                cookiename = parts[0];
                                String path = parts[1];
                                String domain = parts[2];

                                // Got stored domain now see if it matches destination
                                BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                                methodcookie.setDomain(domain);
                                methodcookie.setPath(path);
                                cs.addCookie(methodcookie);
                                if (getDebugHook() != null) {
                                    getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                            methodcookie.toString());
                                }
                            }
                        }
                    } else if (isCookieAllowed(cookiename)) {
                        BasicClientCookie methodcookie = new BasicClientCookie(cookiename, cookieval);
                        String domain = cookie.getDomain();
                        if (domain == null) {
                            try {
                                domain = method.getURI().getHost();
                                domain = domain.substring(domain.indexOf('.'));
                            } catch (Exception e) {
                                domain = "";
                            }
                        }
                        methodcookie.setDomain(domain);
                        String path = cookie.getPath();
                        if (path == null) {
                            path = "/";
                        }
                        methodcookie.setPath(path);
                        cs.addCookie(methodcookie);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpRequest().addCookie(methodcookie.getName(),
                                    methodcookie.toString());
                        }
                    }
                }
            }
        }
    }
    ProxyProfiler.profileTimedRequest(timedObject, "perpareForwardingCookie");
    return true;
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * Convenience method for sending HTTP requests.
 * <b><span style="color:red">Note</span></b>: This method is intended to be
 * used internally, not by end-users.//  www .  java 2s  . co  m
 * 
 * @param baseURL - <b>Example</b>: http://minus.com/api
 * @param parametersBody - The parameters (name => value pairs) to pass to
 *            the request.
 * @param sessionId - If <tt>null</tt> or empty, then create and use a new
 *            session, otherwise, use the specified session_id (which is
 *            stored in a cookie).
 * @param requestType
 * @param additionalRequestHeaders -
 * @param expectedResponseType
 * @return The response retrieved from Minus API.
 * @throws MinusException
 */
private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders,
        final ExpectedResponseType expectedResponseType) throws MinusException {

    DefaultHttpClient client = null;
    HttpRequestBase request = null;
    InputStream responseContent = null;
    boolean errorOccured = false;

    try {
        if (requestType == RequestType.GET) {
            request = new HttpGet(baseURL);
            if (parametersBody != null && !parametersBody.isEmpty()) {
                request = appendParametersToRequest(request, parametersBody);
            }

        } else if (requestType == RequestType.POST) {
            UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody),
                    HTTP.UTF_8);
            request = new HttpPost(baseURL);
            ((HttpPost) request).setEntity(encodedEntity);

        } else {
            throw new MinusException("The method (" + requestType + ") is unknown, weird ...");
        }

        request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT));
        if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) {
            for (Header aHeader : additionalRequestHeaders) {
                request.addHeader(aHeader);
            }
        }

        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);

        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // Execute the request ... pass local context as a parameter
        HttpResponse resp = client.execute(request, localContext);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        Object result = null;
        int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                if (expectedResponseType == ExpectedResponseType.STRING) {
                    result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) {
                    result = entity;
                }
            }
        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine());
            if (request != null) {
                errMsg.append(" : ").append(request.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result, sessionCookie);

    } catch (Exception e) {
        errorOccured = true;
        if (request != null) {
            request.abort();
        }
        String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            // We must not close the client is the expected response is an
            // InputStream. Indeed, if ever we close the client, we won't be
            // able to read the response because of SocketException.
            if (errorOccured) {
                client.getConnectionManager().shutdown();
            } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) {
                client.getConnectionManager().shutdown();
            }
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}