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:messenger.PlurkApi.java

public String plurkAdd(String url) {
    PlurkApi p = PlurkApi.getInstance();
    if (cookiestore == null)
        p.login();/*www . j av  a  2 s.  c  om*/
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpclient.setCookieStore(cookiestore);

    HttpResponse response = null;
    String responseString = null;
    try {
        String content = URLEncoder.encode(url, "UTF-8");
        HttpGet httpget = new HttpGet(getApiUri("/Timeline/plurkAdd?" + "api_key=" + API_KEY + "&" + "content="
                + content + "&" + "qualifier=" + "says" + "&" + "lang=tr_ch"));
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cookiestore = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else {
            System.out.println(response.getStatusLine());
            responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}

From source file:org.mobisocial.corral.CorralTicketProvider.java

public String getDownloadTicket(String objName) throws IOException, JSONException {
    if (SERVER_URL == null) {
        Log.w(TAG, "no file upload service");
        return null;
    }//from w ww.ja v  a 2  s .  com
    String ticket = null;

    // get Identity
    setIdentityAndSignature(null);
    if (myidentity == null) {
        Log.e(TAG, "Failed to get IDENTITY.");
        return null;
    }
    String shortidentity = myidentity.substring(0, 66);
    String url = SERVER_URL + "user/" + shortidentity + "/object/" + objName + "/download-ticket/";
    Log.d(TAG, "Now accessing: " + url);

    // Set up HTTP request
    DefaultHttpClient http = new CertifiedHttpClient(mContext);
    http.setCookieStore(cookieStore);
    HttpGet httpget = new HttpGet(url);
    //      httpget.setHeader( "Connection", "Keep-Alive" );

    HttpResponse response = http.execute(httpget);
    Log.d(TAG, "StatusCode: " + response.getStatusLine().getStatusCode());

    // TODO DELETE
    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        Log.d(TAG, "Header: name=" + header.getName() + ", val=" + header.getValue());
    }
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        Header header = response.getFirstHeader("WWW-Authenticate");
        if (header == null) {
            Log.e(TAG, "Failed to get Corral header.");
            return null;
        }
        String headervalue = header.getValue();
        if (!headervalue.startsWith("Corral=")) {
            Log.e(TAG, "Failed to get Corral header.");
            return null;
        }
        String[] str = headervalue.split("\"");
        String challenge = str[1];
        setIdentityAndSignature(challenge);

        if (mysign == null || myidentity == null) {
            Log.e(TAG, "Failed to get IDENTITY and SIGNATURE.");
            return null;
        }

        httpget.setHeader("Authorization", "Corral " + myidentity + " " + mysign);
        Log.d(TAG, "Corral " + myidentity + " " + mysign);

        response = http.execute(httpget);
        Log.d(TAG, "StatusCode: " + response.getStatusLine().getStatusCode());

    }
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        cookieStore = http.getCookieStore();
        Log.d(TAG, "Saved Cookie: " + cookieStore.getCookies().get(0).getValue());

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String responseStr = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            responseStr += line;
        }
        JSONObject jso = new JSONObject(responseStr);
        ticket = jso.getString("ticket");
        datestr = jso.getString("date");
    }
    return ticket;
}

From source file:org.mobisocial.corral.CorralTicketProvider.java

public String getUploadTicket(String objName, String type, String length, String md5)
        throws IOException, JSONException {
    if (SERVER_URL == null) {
        Log.w(TAG, "no file upload service");
        return null;
    }//from w w w  .ja  v a2  s.  co m
    String ticket = null;

    // get Identity
    setIdentityAndSignature(null);
    if (myidentity == null) {
        Log.e(TAG, "Failed to get IDENTITY.");
        return null;
    }
    String shortidentity = myidentity.substring(0, 66);
    String url = SERVER_URL + "user/" + shortidentity + "/object/" + objName + "/upload-ticket/" + type + "/"
            + length + "/" + md5;
    Log.d(TAG, "Now accessing: " + url);

    // Set up HTTP request
    DefaultHttpClient http = new CertifiedHttpClient(mContext);
    http.setCookieStore(cookieStore);
    HttpGet httpget = new HttpGet(url);
    //      httpget.setHeader( "Connection", "Keep-Alive" );

    HttpResponse response = http.execute(httpget);
    Log.d(TAG, "StatusCode: " + response.getStatusLine().getStatusCode());

    // TODO DELETE
    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        Log.d(TAG, "Header: name=" + header.getName() + ", val=" + header.getValue());
    }
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        Header header = response.getFirstHeader("WWW-Authenticate");
        if (header == null) {
            Log.e(TAG, "Failed to get Corral header.");
            return null;
        }
        String headervalue = header.getValue();
        if (!headervalue.startsWith("Corral=")) {
            Log.e(TAG, "Failed to get Corral header.");
            return null;
        }
        String[] str = headervalue.split("\"");
        String challenge = str[1];
        setIdentityAndSignature(challenge);

        if (mysign == null || myidentity == null) {
            Log.e(TAG, "Failed to get IDENTITY and SIGNATURE.");
            return null;
        }

        httpget.setHeader("Authorization", "Corral " + myidentity + " " + mysign);
        Log.d(TAG, "Corral " + myidentity + " " + mysign);

        response = http.execute(httpget);
        Log.d(TAG, "StatusCode: " + response.getStatusLine().getStatusCode());

    }
    if (response.getStatusLine().getStatusCode() == 200) {
        cookieStore = http.getCookieStore();
        Log.d(TAG, "Saved Cookie: " + cookieStore.getCookies().get(0).getValue());

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String responseStr = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            responseStr += line;
        }
        Log.d(TAG, "Server response:" + responseStr);
        JSONObject jso = new JSONObject(responseStr);
        ticket = jso.getString("ticket");
        datestr = jso.getString("date");
    }

    return ticket;

}

From source file:com.oakley.fon.util.HttpUtils.java

private static DefaultHttpClient getHttpClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient(defaultHttpParams);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }//from   w ww . j ava  2  s . c o  m
        }
    });

    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            // Inflate any responses compressed with gzip
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        // Log.d(TAG, "Decompresing GZIP Response");
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpclient.setCookieStore(null);

    return httpclient;
}

From source file:org.xdi.oxauth.interop.SupportClaimsRequestSpecifyingSubValue.java

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "hostnameVerifier" })
@Test/*w  w w.  j  a  v  a 2 s. c  o m*/
public void supportClaimsRequestSpecifyingSubValueSucceed(final String userId, final String userSecret,
        final String redirectUri, final String redirectUris, String hostnameVerifier) throws Exception {
    showTitle("OC5:FeatureTest-Support claims Request Specifying sub Value (succeed)");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200,
            "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    DefaultHttpClient httpClient = createHttpClient(HostnameVerifierType.fromString(hostnameVerifier));
    CookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);

    List<String> scopes = Arrays.asList("openid", "email");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();

    // 2. Request authorization (first time)
    AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(responseTypes, clientId, scopes,
            redirectUri, nonce);
    authorizationRequest1.setAuthUsername(userId);
    authorizationRequest1.setAuthPassword(userSecret);
    authorizationRequest1.getPrompts().add(Prompt.NONE);
    authorizationRequest1.setState(state);

    AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient1.setRequest(authorizationRequest1);
    AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);

    assertNotNull(authorizationResponse1.getLocation(), "The location is null");
    assertNotNull(authorizationResponse1.getIdToken(), "The ID Token is null");
    assertNotNull(authorizationResponse1.getAccessToken(), "The Access Token is null");
    assertNotNull(authorizationResponse1.getState(), "The state is null");
    assertNotNull(authorizationResponse1.getScope(), "The scope is null");

    String sessionId = authorizationResponse1.getSessionId();

    // 3. Request authorization
    AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(responseTypes, clientId, scopes,
            redirectUri, nonce);
    //authorizationRequest2.setAuthUsername(userId);
    //authorizationRequest2.setAuthPassword(userSecret);
    authorizationRequest2.getPrompts().add(Prompt.NONE);
    authorizationRequest2.setState(state);
    authorizationRequest2.setSessionId(sessionId);

    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest2,
            SignatureAlgorithm.HS256, clientSecret);
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.GIVEN_NAME, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.FAMILY_NAME, ClaimValue.createNull()));
    jwtAuthorizationRequest
            .addIdTokenClaim(new Claim(JwtClaimName.SUBJECT_IDENTIFIER, ClaimValue.createSingleValue(userId)));

    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    authorizationRequest2.setRequest(authJwt);

    AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient2.setRequest(authorizationRequest2);
    AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);

    assertNotNull(authorizationResponse2.getLocation(), "The location is null");
    assertNotNull(authorizationResponse2.getAccessToken(), "The accessToken is null");
    assertNotNull(authorizationResponse2.getTokenType(), "The tokenType is null");
    assertNotNull(authorizationResponse2.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse2.getState(), "The state is null");

    String idToken = authorizationResponse2.getIdToken();
    String accessToken = authorizationResponse2.getAccessToken();

    // 4. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ACCESS_TOKEN_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EMAIL));

    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);

    assertTrue(rsaSigner.validate(jwt));

    // 5. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(userInfoResponse.getStatus(), 200,
            "Unexpected response code: " + userInfoResponse.getStatus());
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.EMAIL));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.GIVEN_NAME));
    assertNotNull(userInfoResponse.getClaim(JwtClaimName.FAMILY_NAME));
}

From source file:com.josue.lottery.eap.service.core.LotoImporter.java

@Override
@Asynchronous/*w w w . ja v a  2  s  . c  om*/
public void importFile() {
    try {

        String urlString = "http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_lotfac.zip";

        DefaultHttpClient client = new DefaultHttpClient();
        CookieStore cookieStore = client.getCookieStore();

        BasicClientCookie cookie = new BasicClientCookie("abc", "123");
        cookie.setDomain("xyz.net");
        cookie.setPath("/");

        cookieStore.addCookie(cookie);
        client.setCookieStore(cookieStore);

        HttpGet request = new HttpGet(urlString);

        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            long len = entity.getContentLength();

            storeFile(entity.getContent());
        }
        System.out.println("### FINISHED ###");
    } catch (IOException ex) {
        logger.error(ex);
    }

}

From source file:com.openx.oauth.client.Helper.java

/**
 * Makes the actual API call/*from w ww  . j a  v  a2 s .co  m*/
 * @param domain
 * @param request
 * @return results from the API
 * @throws IOException 
 */
protected String makeAPICall(String domain, String request) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    OpenXRedirectStrategy dsr = new OpenXRedirectStrategy();
    httpclient.setRedirectStrategy(dsr);

    if (cookieStore == null) {
        createCookieStore(domain, token);
    }

    httpclient.setCookieStore(cookieStore);
    HttpGet httpget = new HttpGet(request);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    String result;
    if (response.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(entity);
    } else {
        result = "";
    }
    return result;
}

From source file:com.openx.oauth.client.Helper.java

/**
 * Validates the access token with the API
 * @param domain/*w ww .j a v a 2s.  c  o  m*/
 * @param token
 * @param path
 * @return success or fail
 * @throws IOException 
 */
public boolean validateToken(String domain, String token, String path) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    OpenXRedirectStrategy dsr = new OpenXRedirectStrategy();
    httpclient.setRedirectStrategy(dsr);

    if (cookieStore == null) {
        createCookieStore(domain, token);
    }

    httpclient.setCookieStore(cookieStore);

    HttpPut httpput = new HttpPut(domain + path + "session/validate");
    HttpResponse response = httpclient.execute(httpput);

    httpclient.getConnectionManager().shutdown();

    boolean valid = true;
    if (response.getStatusLine().getStatusCode() != 200) {
        valid = false;
    }

    return valid;
}

From source file:org.keycloak.adapters.cloned.HttpClientBuilder.java

public HttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {//from  w  ww  .java  2  s.  c  om
        switch (policy) {
        case ANY:
            verifier = new AllowAllHostnameVerifier();
            break;
        case WILDCARD:
            verifier = new BrowserCompatHostnameVerifier();
            break;
        case STRICT:
            verifier = new StrictHostnameVerifier();
            break;
        }
    }
    try {
        SSLSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            sslsf = new SniSSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword,
                    truststore, null, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SniSSLSocketFactory(tlsContext, verifier);
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        registry.register(httpsScheme);
        ClientConnectionManager cm = null;
        if (connectionPoolSize > 0) {
            ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry, connectionTTL,
                    connectionTTLUnit);
            tcm.setMaxTotal(connectionPoolSize);
            if (maxPooledPerRoute == 0)
                maxPooledPerRoute = connectionPoolSize;
            tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
            cm = tcm;

        } else {
            cm = new SingleClientConnManager(registry);
        }
        BasicHttpParams params = new BasicHttpParams();
        params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        if (proxyHost != null) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }

        if (socketTimeout > -1) {
            HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));

        }
        if (establishConnectionTimeout > -1) {
            HttpConnectionParams.setConnectionTimeout(params,
                    (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
        }
        DefaultHttpClient client = new DefaultHttpClient(cm, params);

        if (disableCookieCache) {
            client.setCookieStore(new CookieStore() {
                @Override
                public void addCookie(Cookie cookie) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public List<Cookie> getCookies() {
                    return Collections.emptyList();
                }

                @Override
                public boolean clearExpired(Date date) {
                    return false; //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public void clear() {
                    //To change body of implemented methods use File | Settings | File Templates.
                }
            });

        }
        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.predic8.membrane.test.AssertUtils.java

private static DefaultHttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    DefaultHttpClient hc = new DefaultHttpClient();
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.update(new BasicScheme(), creds);
                }//w w  w.  j  av a 2 s  . co m
            }
        }
    };
    hc.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    hc.setCredentialsProvider(bcp);
    hc.setCookieStore(new BasicCookieStore());
    return hc;
}