Example usage for org.apache.http.client.protocol ClientContext COOKIE_STORE

List of usage examples for org.apache.http.client.protocol ClientContext COOKIE_STORE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol ClientContext COOKIE_STORE.

Prototype

String COOKIE_STORE

To view the source code for org.apache.http.client.protocol ClientContext COOKIE_STORE.

Click Source Link

Document

Attribute name of a org.apache.http.client.CookieStore object that represents the actual cookie store.

Usage

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  ww  w  . j  ava2s .c  o  m*/
        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:crow.api.ApiClient.java

public ApiClient(Context context, Parser parser, ThreadPoolExecutor threadPool, Cache cache,
        CookieStore store) {/* w ww  . j  a  v a  2s  . c  om*/
    this.parser = parser;
    this.threadPool = threadPool;
    this.cache = cache;
    this.handler = new Handler(context.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SEND_MESSAGE:
                RequestRunnable<?, ?> r = (RequestRunnable<?, ?>) msg.obj;
                r.sendMessageToCallback();
                break;
            }
        }
    };
    // Create a local instance of cookie store
    cookieStore = store;
    // Create local HTTP context
    localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.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: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());/*  w ww.  j ava 2s.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:org.zenoss.metrics.reporter.HttpPoster.java

private final void postImpl(MetricBatch batch) throws IOException {
    int size = batch.getMetrics().size();
    MetricCollection metrics = new MetricCollection();
    metrics.setMetrics(batch.getMetrics());

    String json = asJson(metrics);

    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);

    if (needsAuth && !authenticated) {
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        authCache.put(targetHost, basicAuth);

        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }/*from  w  ww  .ja  va  2  s  .co  m*/

    post.setEntity(new StringEntity(json, APPLICATION_JSON));

    cookieJar.clearExpired(new Date());
    httpClient.execute(post, responseHandler, localContext);
}

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

/**
 * Set the cookies to allow to watch more videos and to force to use english.
 *//*from  w w  w.  j  av  a2 s .  c o  m*/
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:org.thomnichols.android.gmarks.BookmarksQueryService.java

private BookmarksQueryService(String userAgent) {
    //      java.util.logging.Logger.getLogger("httpclient.wire.header").setLevel(java.util.logging.Level.FINEST);
    //      java.util.logging.Logger.getLogger("httpclient.wire.content").setLevel(java.util.logging.Level.FINEST);
    ctx = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    String defaultUA = "Mozilla/5.0 (Linux; U; Android 2.1; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3";
    //      http = new DefaultHttpClient();
    http = AndroidHttpClient.newInstance(userAgent != null ? userAgent : defaultUA);
}

From source file:org.lol.reddit.account.RedditAccount.java

public static LoginResultPair login(final Context context, final String username, final String password,
        final HttpClient client) {

    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
    fields.add(new BasicNameValuePair("user", username));
    fields.add(new BasicNameValuePair("passwd", password));
    fields.add(new BasicNameValuePair("api_type", "json"));

    // TODO put somewhere else
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");
    request.setParams(params);/*from  ww  w. j a v  a 2 s .  c  o  m*/

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        return new LoginResultPair(LoginResult.INTERNAL_ERROR);
    }

    final PersistentCookieStore cookies = new PersistentCookieStore();

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    final StatusLine status;
    final HttpEntity entity;
    try {
        final HttpResponse response = client.execute(request, localContext);
        status = response.getStatusLine();
        entity = response.getEntity();

    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    if (status.getStatusCode() != 200) {
        return new LoginResultPair(LoginResult.REQUEST_ERROR);
    }

    final JsonValue result;

    try {
        result = new JsonValue(entity.getContent());
        result.buildInThisThread();
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    final String modhash;

    try {

        // TODO use the more general reddit error finder
        final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors");
        errors.join();
        if (errors.getCurrentItemCount() != 0) {

            for (final JsonValue v : errors) {
                for (final JsonValue s : v.asArray()) {

                    // TODO handle unknown messages by concatenating all Reddit's strings

                    if (s.getType() == JsonValue.Type.STRING) {

                        Log.i("RR DEBUG ERROR", s.asString());

                        // lol, reddit api
                        if (s.asString().equalsIgnoreCase("WRONG_PASSWORD")
                                || s.asString().equalsIgnoreCase("invalid password")
                                || s.asString().equalsIgnoreCase("passwd"))
                            return new LoginResultPair(LoginResult.WRONG_PASSWORD);

                        if (s.asString().contains("too much")) // also "RATELIMIT", but that's not as descriptive
                            return new LoginResultPair(LoginResult.RATELIMIT, s.asString());
                    }
                }
            }

            return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR);
        }

        final JsonBufferedObject data = result.asObject().getObject("json").getObject("data");

        modhash = data.getString("modhash");

    } catch (NullPointerException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (InterruptedException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    }

    return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null);
}

From source file:ui.shared.URLReader.java

public URLReader(String scheme, String host, String path, String query, String key) {
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    contents = this.getStringFromPOST(scheme, host, path, query, key);
    // contents = this.getStringFromURLPOST(scheme, host, path, query, key);
}

From source file:de.mojadev.ohmmarks.virtuohm.VirtuOhmHTTPHandler.java

private void setupHttpIO() {
    Log.d("Communicator", "Instanciating HTTP Client");
    httpIO = AndroidHttpClient.newInstance(USER_AGENT);
    if (this.cookies == null) {
        // Setup a cookie store for the httpContext, so we don't have to care about them
        this.cookies = new BasicCookieStore();
        this.httpContext = new BasicHttpContext();

        this.httpContext.setAttribute(ClientContext.COOKIE_STORE, this.cookies);
    }//from   ww  w  . j a v a  2 s  .c  o m

}