Example usage for org.apache.http.impl.cookie BasicClientCookie setVersion

List of usage examples for org.apache.http.impl.cookie BasicClientCookie setVersion

Introduction

In this page you can find the example usage for org.apache.http.impl.cookie BasicClientCookie setVersion.

Prototype

public void setVersion(final int version) 

Source Link

Document

Sets the version of the cookie specification to which this cookie conforms.

Usage

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from  w w w. ja  v  a2s .  c o m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.kms.core.io.HttpUtil_In.java

public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) {
    CloseableHttpClient httpclient;/*w  w w.  j a  va2 s  .  c om*/

    // Auth Scheme 
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    // NTLM  
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080),
            new NTCredentials(SoeID, Password, "dummy", "APAC"));
    //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" ));

    // ------------- cookie start ------------------------
    // Auction   
    // Create a local instance of cookie store
    final CookieStore cookieStore = new BasicCookieStore();

    //       Cookie  .
    final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES");
    cookie.setVersion(0);
    cookie.setDomain(".scourt.go.kr");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    // ------------- cookie end ------------------------

    if (type == 0) // TYPE.AuctionInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else // SagunInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build();
    }

    return httpclient;
}

From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java

public static String get(String url, Cookie[] cookies) {
    String body = null;/*from www  .j  a v  a  2 s .c  o m*/
    try {
        StringBuffer buffer = new StringBuffer();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);

        httpClient.setCookieStore(new BasicCookieStore());
        for (int i = 0; i < cookies.length; i++) {
            logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":"
                    + cookies[i].getDomain() + ":" + cookies[i].getPath());
            BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue());
            cookie.setVersion(0);
            URL urlParse = new URL(url);
            String host = urlParse.getHost();
            String domain = null;
            if (host != null && host.indexOf('.') > 0) {
                domain = host.substring(host.indexOf('.') + 1);
            }
            logger.finest("Domain:" + domain);
            cookie.setDomain(domain);
            cookie.setPath("/");

            httpClient.getCookieStore().addCookie(cookie);
        }
        HttpResponse response = httpClient.execute(getRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        logger.finest("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.finest(output);
            buffer.append(output);
        }

        httpClient.getConnectionManager().shutdown();

        body = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return body;
}

From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java

public static String post(String url, Cookie[] cookies, String content) {
    String body = null;/*from w w  w. j a v a2 s . c om*/
    try {
        StringBuffer buffer = new StringBuffer();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        httpClient.setCookieStore(new BasicCookieStore());
        String hostName = new URL(url).getHost();
        String domain = hostName.substring(hostName.indexOf("."));
        for (int i = 0; i < cookies.length; i++) {
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":"
                        + cookies[i].getDomain() + ":" + cookies[i].getPath());
            }
            BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue());
            cookie.setVersion(0);
            cookie.setDomain(domain);
            cookie.setPath("/");

            httpClient.getCookieStore().addCookie(cookie);
        }
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Output from Server .... \n");
        }
        while ((output = br.readLine()) != null) {
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest(output);
            }
            buffer.append(output);
        }

        httpClient.getConnectionManager().shutdown();

        body = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return body;
}

From source file:org.freaknet.gtrends.client.GoogleTrendsClientFactory.java

private static GoogleTrendsClient _parse(CmdLineParser cmdLine) throws GoogleTrendsClientRunException {
    setLogLevel(cmdLine);/*from   w  ww  .j  a v  a  2s  .com*/
    try {
        // TODO - Move outside
        // Prints all available regions and exists
        if (cmdLine.getPrintRegionsOpt()) {
            RegionParser.getInstance().printAll();
            System.exit(0);
        }

        // HTTP Client setup
        int timeout = 5; // seconds
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
                .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
        _httpClient = HttpClientBuilder.create().setDefaultCookieStore(_cookieStore)
                .setDefaultRequestConfig(config)
                //.setRedirectStrategy(new LaxRedirectStrategy())
                .build();

        BasicClientCookie cookie = new BasicClientCookie("I4SUserLocale", "it");
        cookie.setVersion(0);
        cookie.setDomain("www.google.com");
        cookie.setPath("/trends");
        cookie.setSecure(false);
        _cookieStore.addCookie(cookie);

        cookie = new BasicClientCookie("PREF", "");
        cookie.setVersion(0);
        cookie.setDomain("www.google.com");
        cookie.setPath("/trends");
        cookie.setSecure(false);
        _cookieStore.addCookie(cookie);

        // TODO - fix proxy
        //      if (cmdLine.getProxyHostname() != null) {
        //        HttpHost proxyHost = new HttpHost(cmdLine.getProxyHostname(), cmdLine.getProxyPort(), cmdLine.getProxyProtocol());
        //        Credentials credentials = cmdLine.getProxyCredentials();
        //        if (credentials != null) {
        //          _httpClient.get
        //          _httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        //        }
        //        _httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        //      }
        // Setup Google Authenticator
        _authenticator = new GoogleAuthenticator(cmdLine.getUsername(), cmdLine.getPassword(), _httpClient);

    } catch (FileNotFoundException ex) {
        throw new GoogleTrendsClientRunException(ex);
    }

    return new GoogleTrendsClient(_authenticator, _httpClient);
}

From source file:cn.ttyhuo.common.MyApplication.java

public static void setUpPersistentCookieStore() {
    if (context == null)
        return;/*  w  w  w. ja  v a 2 s . c  o  m*/
    cookieStore = new PersistentCookieStore(context);

    CookieStore httpCookieStore = HttpRequestUtil.cookieManager.getCookieStore();
    for (HttpCookie h : httpCookieStore.getCookies()) {
        BasicClientCookie newCookie = new BasicClientCookie(h.getName(), h.getValue());
        newCookie.setVersion(h.getVersion());
        newCookie.setDomain(h.getDomain());
        newCookie.setPath(h.getPath());
        newCookie.setSecure(h.getSecure());
        newCookie.setComment(h.getComment());
        cookieStore.addCookie(newCookie);
    }
}

From source file:org.apache.olingo.samples.client.core.http.CookieHttpClientFactory.java

@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
    final CookieStore cookieStore = new BasicCookieStore();

    // Populate cookies if needed
    final BasicClientCookie cookie = new BasicClientCookie("name", "value");
    cookie.setVersion(0);
    cookie.setDomain(".mycompany.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);/*  w  w  w.ja  va 2s  .c  om*/

    final DefaultHttpClient httpClient = super.create(method, uri);
    httpClient.setCookieStore(cookieStore);

    return httpClient;
}

From source file:com.evozi.droidsniff.objects.CookieWrapper.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String domain = (String) in.readObject();
    String name = (String) in.readObject();
    String path = (String) in.readObject();
    String value = (String) in.readObject();

    BasicClientCookie cookie = new BasicClientCookie(name, value);
    cookie.setDomain(domain);// w ww  .j  av  a2  s .c o  m
    cookie.setPath(path);
    cookie.setVersion(0);

    this.cookie = cookie;
}

From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.SiteMinderAuthenticator.java

/**
 * @return the list of SiteMinder cookies that have to be added to the HTTP request in order to authenticate it.
 *///from   w ww.j  a va 2  s  .  c  om
private List<Cookie> getSiteMinderCookies() {
    javax.servlet.http.Cookie[] receivedCookies = ((ServletRequest) container.getRequest())
            .getHttpServletRequest().getCookies();
    List<Cookie> cookies = new ArrayList<Cookie>();
    // Look for the SMSESSION cookie.
    for (int i = 0; i < receivedCookies.length; i++) {
        javax.servlet.http.Cookie receivedCookie = receivedCookies[i];
        if (SITE_MINDER_COOKIES.contains(receivedCookie.getName())) {
            BasicClientCookie cookie = new BasicClientCookie(receivedCookie.getName(),
                    receivedCookie.getValue());
            cookie.setVersion(receivedCookie.getVersion());
            cookie.setDomain(receivedCookie.getDomain());
            cookie.setPath(receivedCookie.getPath());
            cookie.setSecure(receivedCookie.getSecure());
            // Set attributes EXACTLY as sent by the browser.
            cookie.setAttribute(ClientCookie.VERSION_ATTR, String.valueOf(receivedCookie.getVersion()));
            cookie.setAttribute(ClientCookie.DOMAIN_ATTR, receivedCookie.getDomain());
            cookies.add(cookie);
        }
    }
    return cookies;
}

From source file:com.jaspersoft.android.jaspermobile.network.cookie.CookieMapper.java

@Nullable
public org.apache.http.cookie.Cookie toApacheCookie(@Nullable HttpCookie cookie) {
    if (cookie == null) {
        return null;
    }//from   ww  w. ja v a2s .  c  o m

    BasicClientCookie clientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
    clientCookie.setDomain(cookie.getDomain());
    clientCookie.setPath(cookie.getPath());
    clientCookie.setVersion(cookie.getVersion());

    Date expiryDate = new Date(new Date().getTime() + cookie.getMaxAge());
    clientCookie.setExpiryDate(expiryDate);

    return clientCookie;
}