Example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore

List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore.

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:com.wareninja.opensource.discourse.utils.MyWebClient.java

protected void initBase() {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);

    httpRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
            .setCookieSpec(CookieSpecs.BEST_MATCH).build();

    cookieStore = new BasicCookieStore();

    httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(httpRequestConfig).build();

    localContext = HttpClientContext.create();

}

From source file:neembuu.release1.externalImpl.linkhandler.DailymotionLinkHandlerProvider.java

/**
 * Set the cookies to allow to watch more videos and to force to use english.
 *///  w w w  .j  a va  2  s  .com
private void setCookies() {
    httpContext = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();

    //Add the cookies value
    cookieStore.addCookie(new BasicClientCookie("family_filter", "off"));
    cookieStore.addCookie(new BasicClientCookie("ff", "off"));
    cookieStore.addCookie(new BasicClientCookie("lang", "en_US"));

    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

}

From source file:ui.shared.URLReader.java

public URLReader(String scheme, String host, String path, String query) {
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    // url = new URL(scheme+"://"+host+path+"/"+query);
    contents = this.getStringFromURLGET(scheme, host, path, query);
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {//from w w  w  .ja v  a 2  s.  c om
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:sabina.integration.TestScenario.java

TestScenario(String backend, int port, boolean secure, boolean externalFiles) {
    this.port = port;
    this.backend = backend;
    this.secure = secure;
    this.externalFiles = externalFiles;

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslFactory(),
            ALLOW_ALL_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslConnectionSocketFactory).build();

    HttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(socketFactoryRegistry,
            new ManagedHttpClientConnectionFactory());

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.NETSCAPE).build();
    cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    this.httpClient = HttpClients.custom().setSchemePortResolver(h -> {
        Args.notNull(h, "HTTP host");
        final int port1 = h.getPort();
        if (port1 > 0) {
            return port1;
        }// w w  w. ja  va 2  s.  co  m

        final String name = h.getSchemeName();
        if (name.equalsIgnoreCase("http")) {
            return port1;
        } else if (name.equalsIgnoreCase("https")) {
            return port1;
        } else {
            throw new UnsupportedSchemeException("unsupported protocol: " + name);
        }
    }).setConnectionManager(connManager).setDefaultRequestConfig(globalConfig).build();
}

From source file:org.auraframework.integration.test.configuration.JettyTestServletConfig.java

@Override
public HttpClient getHttpClient() {
    /*/*from   w w  w .j a v a  2s .  co m*/
     * 10 minute timeout for making a connection and for waiting for data on the connection. This prevents tests
     * from hanging in the http code, which in turn can prevent the server from exiting.
     */
    int timeout = 10 * 60 * 1000;

    CookieStore cookieStore = new BasicCookieStore();

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);

    DefaultHttpClient http = new DefaultHttpClient(params);
    http.setCookieStore(cookieStore);

    return http;
}

From source file:org.wso2.carbon.appmgt.impl.publishers.WSO2ExternalAppStorePublisher.java

@Override
public void publishToStore(WebApp webApp, AppStore store) throws AppManagementException {
    if (log.isDebugEnabled()) {
        String msg = String.format("Start publishing web app : %s to external store : %s ", webApp.getApiName(),
                store.getName());/*from w w w .  ja  v a 2  s .c  o  m*/
        log.debug(msg);
    }

    validateStore(store);

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    String storeEndpoint = store.getEndpoint();
    HttpClient httpClient = AppManagerUtil.getHttpClient(storeEndpoint);
    String provider = AppManagerUtil.replaceEmailDomain(store.getUsername());
    //login
    loginToExternalStore(store, httpContext, httpClient);
    //create app
    String assetId = addAppToStore(webApp, storeEndpoint, provider, httpContext, httpClient);
    //add tags
    addTags(webApp, assetId, storeEndpoint, httpContext, httpClient);
    //publish app
    publishAppToStore(assetId, storeEndpoint, httpContext, httpClient);
    //logout
    logoutFromExternalStore(storeEndpoint, httpContext, httpClient);

}

From source file:com.glaf.core.util.http.HttpClientUtils.java

/**
 * ??POST//from   ww w  . j av  a 2  s .c  o  m
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doPost(String url, String encoding, Map<String, String> dataMap) {
    StringBuffer buffer = new StringBuffer();
    HttpPost post = null;
    InputStreamReader is = null;
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        post = new HttpPost(url);
        if (dataMap != null && !dataMap.isEmpty()) {
            List<org.apache.http.NameValuePair> nameValues = new ArrayList<org.apache.http.NameValuePair>();
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                nameValues.add(new BasicNameValuePair(name, value));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValues, encoding);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        if (post != null) {
            post.releaseConnection();
        }
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:edu.mit.scratch.ScratchUser.java

public void setFollowing(final ScratchSession session, final boolean following) throws ScratchUserException {
    try {/*from  w w  w  .ja  v  a2  s  .  c  om*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final BasicCookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie sessionid = new BasicClientCookie("scratchsessionsid", session.getSessionID());
        final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken());
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        sessionid.setDomain(".scratch.mit.edu");
        sessionid.setPath("/");
        token.setDomain(".scratch.mit.edu");
        token.setPath("/");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(sessionid);
        cookieStore.addCookie(token);
        cookieStore.addCookie(debug);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.put()
                .setUri("https://scratch.mit.edu/site-api/users/followers/" + this.getUsername() + "/"
                        + ((following) ? "add" : "remove") + "/?usernames=" + session.getUsername())
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/")
                .addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("Content-Encoding", "gzip").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",
                        "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken="
                                + session.getCSRFToken())
                .addHeader("X-CSRFToken", session.getCSRFToken()).build();
        try {
            resp = httpClient.execute(update);
            if (resp.getStatusLine().getStatusCode() != 200)
                throw new ScratchUserException();
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        // result = your json data
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }
}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void notAuthorized() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    // first authenticate with the login servlet
    final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login");
    final List<NameValuePair> data = new ArrayList<NameValuePair>() {
        {//from  ww w  . j  av  a 2s  .  c  o  m
            add(new BasicNameValuePair("username", "userB"));
            add(new BasicNameValuePair("password", "secret"));
        }
    };
    httpPost.setEntity(new UrlEncodedFormEntity(data));
    final CloseableHttpResponse respLogin = client.execute(httpPost);
    try {
        assertEquals(200, respLogin.getStatusLine().getStatusCode());

    } finally {
        respLogin.close();
    }

    // then we can just call the hello servlet
    final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello");
    final CloseableHttpResponse resp = client.execute(httpGet);
    try {
        assertEquals(403, resp.getStatusLine().getStatusCode());

    } finally {
        resp.close();
    }
}