Example usage for org.apache.commons.httpclient HttpState addCookies

List of usage examples for org.apache.commons.httpclient HttpState addCookies

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpState addCookies.

Prototype

public void addCookies(Cookie[] paramArrayOfCookie) 

Source Link

Usage

From source file:com.liferay.util.Http.java

public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException {

    byte[] byteArray = null;

    HttpMethod method = null;/* w ww  . j  a v  a  2 s.co m*/

    try {
        HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

        if (location == null) {
            return byteArray;
        } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) {

            location = HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfig = new HostConfiguration();

        hostConfig.setHost(new URI(location));

        if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) {
            hostConfig.setProxy(PROXY_HOST, PROXY_PORT);
        }

        client.setHostConfiguration(hostConfig);
        client.setConnectionTimeout(5000);
        client.setTimeout(5000);

        if (cookies != null && cookies.length > 0) {
            HttpState state = new HttpState();

            state.addCookies(cookies);
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);

            client.setState(state);
        }

        if (post) {
            method = new PostMethod(location);
        } else {
            method = new GetMethod(location);
        }

        method.setFollowRedirects(true);

        client.executeMethod(method);

        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            return URLtoByteArray(locationHeader.getValue(), cookies, post);
        }

        InputStream is = method.getResponseBodyAsStream();

        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];

            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {

                buffer.write(bytes, 0, i);
            }

            byteArray = buffer.toByteArray();

            is.close();
            buffer.close();
        }

        return byteArray;
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception e) {
            Logger.error(Http.class, e.getMessage(), e);
        }
    }
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

/** Returns a HttpState fixed with cookies.
 *
 * @since 0.8.0/*  w  w w  .  j a v a2s  . co  m*/
 */
protected HttpState preparedHttpState() {
    HttpState state = new HttpState();

    if (cookies != null) {
        // Add cookies to the state
        state.addCookies(cookies);
    }

    if (log.isDebugEnabled()) {
        Cookie[] _cookies = state.getCookies();
        debugCookies(_cookies);
    }

    return state;
}

From source file:com.liferay.portal.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;//from   w  w w.  j  a va  2s  . c o m
    HttpState httpState = null;

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) | ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if ((cookies != null) && (cookies.length > 0)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            Header contentLength = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLength != null) {
                response.setContentLength(GetterUtil.getInteger(contentLength.getValue()));
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            bytes = FileUtil.getBytes(inputStream);
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId,
        PortletRequest portletRequest) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;//  w ww . j a va2s  . co m
    HttpState httpState = null;

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) {

                    HttpClientParams httpClientParams = httpClient.getParams();

                    httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8);
                }

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if (ArrayUtil.isNotEmpty(cookies)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        response.setResponseCode(responseCode);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects, progressId, portletRequest);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            int contentLength = 0;

            Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLengthHeader != null) {
                contentLength = GetterUtil.getInteger(contentLengthHeader.getValue());

                response.setContentLength(contentLength);
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            if (Validator.isNotNull(progressId) && (portletRequest != null)) {

                ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream,
                        contentLength, progressId);

                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(
                        contentLength);

                try {
                    progressInputStream.readAll(unsyncByteArrayOutputStream);
                } finally {
                    progressInputStream.clearProgress();
                }

                bytes = unsyncByteArrayOutputStream.unsafeGetByteArray();

                unsyncByteArrayOutputStream.close();
            } else {
                bytes = FileUtil.getBytes(inputStream);
            }
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:org.apache.cactus.internal.client.connector.http.HttpClientConnectionHelper.java

/**
 * {@inheritDoc}//from   w ww . ja  v a2  s. c om
 * @see ConnectionHelper#connect(WebRequest, Configuration)
 */
public HttpURLConnection connect(WebRequest theRequest, Configuration theConfiguration) throws Throwable {
    URL url = new URL(this.url);

    HttpState state = new HttpState();

    // Choose the method that we will use to post data :
    // - If at least one parameter is to be sent in the request body, then
    //   we are doing a POST.
    // - If user data has been specified, then we are doing a POST
    if (theRequest.getParameterNamesPost().hasMoreElements() || (theRequest.getUserData() != null)) {
        this.method = new PostMethod();
    } else {
        this.method = new GetMethod();
    }

    // Add Authentication headers, if necessary. This is the first
    // step to allow authentication to add extra headers, HTTP parameters,
    // etc.
    Authentication authentication = theRequest.getAuthentication();

    if (authentication != null) {
        authentication.configure(state, this.method, theRequest, theConfiguration);
    }

    // Add the parameters that need to be passed as part of the URL
    url = HttpUtil.addHttpGetParameters(theRequest, url);

    this.method.setFollowRedirects(false);
    this.method.setPath(UrlUtil.getPath(url));
    this.method.setQueryString(UrlUtil.getQuery(url));

    // Sets the content type
    this.method.setRequestHeader("Content-type", theRequest.getContentType());

    // Add the other header fields
    addHeaders(theRequest);

    // Add the POST parameters if no user data has been specified (user data
    // overried post parameters)
    if (theRequest.getUserData() != null) {
        addUserData(theRequest);
    } else {
        addHttpPostParameters(theRequest);
    }

    // Add the cookies to the state
    state.addCookies(CookieUtil.createHttpClientCookies(theRequest, url));

    // Open the connection and get the result
    HttpClient client = new HttpClient();
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(url.getHost(), url.getPort(), Protocol.getProtocol(url.getProtocol()));
    client.setState(state);
    client.executeMethod(hostConfiguration, this.method);

    // Wrap the HttpClient method in a java.net.HttpURLConnection object
    return new org.apache.commons.httpclient.util.HttpURLConnection(this.method, url);
}

From source file:org.apache.cactus.internal.util.TestCookieUtil.java

/**
 * Verify that an HttpClient HttpState object can be created when
 * no Cactus cookies have been defined.// ww  w .  ja va 2  s  .  com
 * 
 * @exception Exception on error
 */
public void testCreateHttpStateWhenNoCactusCookieDefined() throws Exception {
    WebRequest request = new WebRequestImpl();
    HttpState state = new HttpState();
    state.addCookies(CookieUtil.createHttpClientCookies(request, new URL("http://jakarta.apache.org")));
    assertEquals(0, state.getCookies().length);
}

From source file:org.apache.cactus.internal.util.TestCookieUtil.java

/**
 * Verify that an HttpClient HttpState object can be created when
 * several Cactus cookies exist./*from   w ww  .  j a v a 2 s  .  c  om*/
 * 
 * @exception Exception on error
 */
public void testCreateHttpStateWhenSeveralCactusCookieExist() throws Exception {
    WebRequest request = new WebRequestImpl();
    request.addCookie(new Cookie("domain1", "name1", "value1"));
    request.addCookie(new Cookie("domain2", "name2", "value2"));

    HttpState state = new HttpState();
    state.addCookies(CookieUtil.createHttpClientCookies(request, new URL("http://jakarta.apache.org")));

    assertEquals(2, state.getCookies().length);
}

From source file:org.seasr.meandre.components.tools.text.io.ReadContentWithCookie.java

@Override
public void executeCallBack(ComponentContext cc) throws Exception {
    URI uri = DataTypeParser.parseAsURI(cc.getDataComponentFromInput(IN_LOCATION));
    Cookie[] cookies = (Cookie[]) cc.getDataComponentFromInput(IN_COOKIE);

    cc.pushDataComponentToOutput(OUT_LOCATION, BasicDataTypesTools.stringToStrings(uri.toString()));

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(uri.toString());
    HttpState initialState = new HttpState();
    initialState.addCookies(cookies);
    client.setState(initialState);//from   w  ww.  ja va2s  .c  om
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

    try {
        client.executeMethod(method);
        byte[] baRes = method.getResponseBody();
        method.releaseConnection();
        cc.pushDataComponentToOutput(OUT_RAW_DATA, BasicDataTypesTools.byteArrayToBytes(baRes));
    } finally {
        method.releaseConnection();
    }
}