Example usage for org.apache.http.impl.client DefaultHttpClient setCookieStore

List of usage examples for org.apache.http.impl.client DefaultHttpClient setCookieStore

Introduction

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

Prototype

public synchronized void setCookieStore(final CookieStore cookieStore) 

Source Link

Usage

From source file:org.opensourcetlapp.tl.TLLib.java

public static void subscribeThread(String topicId) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCookieStore(cookieStore);

    HttpPost httpost = new HttpPost(SUB_URL);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("action", "toggleSub"));
    nvps.add(new BasicNameValuePair("thread_id", topicId));
    nvps.add(new BasicNameValuePair("token", tokenField));
    Log.d(TAG, "Subscribing Thread");

    try {//from w  w w .  ja va2  s  .  c om
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            entity.consumeContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static void postMessage(String message, String backurl, String topicId, Context context)
        throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCookieStore(cookieStore);
    HttpPost httpost = new HttpPost(POST_URL);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("bericht", message));
    nvps.add(new BasicNameValuePair("stage", "1"));
    nvps.add(new BasicNameValuePair("backurl", backurl));
    nvps.add(new BasicNameValuePair("token", tokenField));
    nvps.add(new BasicNameValuePair("topic_id", topicId));
    nvps.add(new BasicNameValuePair("submit_button", "Post"));

    try {// w w w. j av  a2s .c  o m
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            entity.consumeContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static void sendPM(String to, String subject, String message) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCookieStore(cookieStore);
    HttpPost httpost = new HttpPost(PM_URL);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("to", to));
    nvps.add(new BasicNameValuePair("subject", subject));
    nvps.add(new BasicNameValuePair("body", message));
    nvps.add(new BasicNameValuePair("view", "Send"));
    nvps.add(new BasicNameValuePair("token", tokenField));
    Log.d(TAG, "Sending message");
    Log.d(TAG, to);/*from  ww  w. j av a  2s.  co  m*/
    Log.d(TAG, subject);
    Log.d(TAG, message);

    try {
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            entity.consumeContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static TagNode TagNodeFromURLEx2(HtmlCleaner cleaner, URL url, Handler handler, Context context,
        String fullTag, boolean login) throws IOException {

    handler.sendEmptyMessage(PROGRESS_CONNECTING);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (cookieStore != null) {
        httpclient.setCookieStore(cookieStore);
    }/*from  w ww  .jav a2  s  .  c om*/
    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);
    if (cookieStore == null) {
        cookieStore = httpclient.getCookieStore();
    }

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    HttpEntity httpEntity = response.getEntity();
    InputStream is = httpEntity.getContent();
    return TagNodeFromURLHelper(is, fullTag, handler, context, cleaner);
}

From source file:ca.sqlpower.wabit.enterprise.client.WabitClientSession.java

public static HttpClient createHttpClient(SPServerInfo serviceInfo) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 2000);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.setCookieStore(cookieStore);
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(serviceInfo.getServerAddress(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(serviceInfo.getUsername(), serviceInfo.getPassword()));
    return httpClient;
}

From source file:bear.plugins.java.JenkinsCache.java

public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri,
        String user, String pass) {
    try {//from w ww.  j ava2s  .c o m
        Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion);

        if (!optional.isPresent()) {
            throw new RuntimeException("could not find: " + jdkVersion);
        }

        String uri = optional.get().filepath;

        SSLContext sslContext = SSLContext.getInstance("TLSv1");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);

        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();

        Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(httpScheme);

        DefaultHttpClient httpClient = new DefaultHttpClient(
                new PoolingClientConnectionManager(schemeRegistry));

        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("gpw_e24", ".");
        cookie.setDomain("oracle.com");
        cookie.setPath("/");
        cookie.setSecure(true);

        cookieStore.addCookie(cookie);

        httpClient.setCookieStore(cookieStore);

        HttpPost httppost = new HttpPost("https://login.oracle.com");

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        HttpResponse response = httpClient.execute(httppost);

        int code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("unable to auth: " + code);
        }

        // closes the single connection
        //                EntityUtils.consumeQuietly(response.getEntity());

        httppost = new HttpPost(uri);

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        response = httpClient.execute(httppost);

        code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("to download: " + uri);
        }

        File file = new File(tempDestDir, optional.get().name);
        HttpEntity entity = response.getEntity();

        final long length = entity.getContentLength();

        final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file));

        System.out.printf("Downloading %s to %s...%n", uri, file);

        Thread progressThread = new Thread(new Runnable() {
            double lastProgress;

            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    long copied = os.getCount();

                    double progress = copied * 100D / length;

                    if (progress != lastProgress) {
                        System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1));
                    }

                    lastProgress = progress;

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        }, "progressThread");

        progressThread.start();

        ByteStreams.copy(entity.getContent(), os);

        progressThread.interrupt();

        System.out.println("Download complete.");

        return file;
    } catch (Exception e) {
        throw Exceptions.runtime(e);
    }
}

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);/*  w  ww. j  a v a 2  s  . c  o m*/
    cookie.setDomain(".mycompany.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

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

    return httpClient;
}

From source file:net.nym.library.cookie.CookieTest.java

private String getRequest(Context context, String urlString, Map<String, Object> params) throws IOException {
    StringBuffer param = new StringBuffer();
    int i = 0;//from   w w  w . j a  v a2s . com
    for (String key : params.keySet()) {
        if (i == 0)
            param.append("?");
        else
            param.append("&");
        param.append(key).append("=").append(params.get(key));
        i++;
    }

    Log.i(urlString + param.toString());
    //URL?
    HttpGet getMethod = new HttpGet(urlString + param.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    client.setCookieStore(new PersistentCookieStore(context));
    HttpResponse response = client.execute(getMethod);
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        return result;
    }
    return null;
}

From source file:com.domuslink.communication.ApiHandler.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}.//from  ww w.j ava 2  s  .  c  o m
 *
 * @param type The type of either a GET or POST for the request
 * @param commandURI The constructed URI for the path
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler)
        throws ApiException {
    HttpResponse response;
    HttpRequestBase request;

    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    client.setCredentialsProvider(credsProvider);
    CookieStore cookieStore = cookieHandler.getCookieStore();
    if (cookieStore != null) {
        boolean expiredCookies = false;
        Date nowTime = new Date();
        for (Cookie theCookie : cookieStore.getCookies()) {
            if (theCookie.isExpired(nowTime))
                expiredCookies = true;
        }
        if (!expiredCookies)
            client.setCookieStore(cookieStore);
        else {
            cookieHandler.setCookieStore(null);
            cookieStore = null;
        }
    }

    try {
        if (type == POST_TYPE)
            request = new HttpPost(commandURI);
        else
            request = new HttpGet(commandURI);

        request.setHeader("User-Agent", sUserAgent);
        response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            Log.e(TAG,
                    "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString());
            throw new ApiException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        if (cookieStore == null) {
            List<Cookie> realCookies = client.getCookieStore().getCookies();
            if (!realCookies.isEmpty()) {
                BasicCookieStore newCookies = new BasicCookieStore();
                for (int i = 0; i < realCookies.size(); i++) {
                    newCookies.addCookie(realCookies.get(i));
                    //                      Log.d(TAG, "aCookie - " + realCookies.get(i).toString());
                }
                cookieHandler.setCookieStore(newCookies);
            }
        }

        // Return result from buffered stream
        return content.toString();
    } catch (IOException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:de.devbliss.apitester.ApiTesterModule.java

@Provides
public TestState provideTestState(CookieStore cookieStore) {
    // when creating an HttpClient, we need to also create a CookieStore if we ever want to
    // access its cookies, and both of these need to be bound together. If they were bound
    // as singleton, that wouldn't work, because you could only ever have one session, you
    // couldn't have a test client, admin client, user client, friend client etc. If they
    // are not bound as singleton, then there would be no way to access them together, you
    // could have a cookie store injected, and a client injected, but it wouldn't be the
    // cookie store for that client. So, we can't have Guice manage them. Instead, we
    // have Guice manage the TestState, not singleton, and instantiate the client ourselves.
    DefaultHttpClient client = new DefaultHttpClient();
    client.setCookieStore(cookieStore);
    return new TestState(client, cookieStore);
}