List of usage examples for org.apache.http.impl.client DefaultHttpClient setCookieStore
public synchronized void setCookieStore(final CookieStore cookieStore)
From source file:org.auraframework.integration.test.configuration.JettyTestServletConfig.java
@Override public HttpClient getHttpClient() { /*//from ww w .j a v a2 s . c o 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:bear.plugins.java.JenkinsCache.java
public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {//from w w w. ja va 2s . 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; // agent.get() // agent.get() 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(); schemeRegistry.register(httpsScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); MechanizeAgent agent = new MechanizeAgent(); Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com"); cookie2.getHttpCookie().setPath("/"); cookie2.getHttpCookie().setSecure(false); 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); } // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); 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:thiru.in.basicauthwebview.Authenticate.java
@Override protected CookieStore doInBackground(String... data) { String url = data[0];// w w w . jav a2 s.c om List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("token", data[1])); DefaultHttpClient httpClient = new DefaultHttpClient(); BasicCookieStore cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { Log.i("Cookie", cookie.getName() + " ==> " + cookie.getValue()); } } else { Log.i("Authenticate", "Invalid user and password combination"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return cookieStore; }
From source file:org.opensourcetlapp.tl.TLLib.java
public static boolean login(String login, String pw, Handler handler, Context context) throws IOException { handler.sendEmptyMessage(TLHandler.PROGRESS_LOGIN); logout();//from www.j a va 2s . c om // Fetch the token HtmlCleaner cleaner = TLLib.buildDefaultHtmlCleaner(); URL url = new URL(LOGIN_URL); //TagNode node = TagNodeFromURLEx2(cleaner, url, handler, context, "<html>", false); TagNode node = TLLib.TagNodeFromURLLoginToken(cleaner, url, handler, context); String token = null; try { TagNode result = (TagNode) (node.evaluateXPath("//input")[0]); token = result.getAttributeByName("value"); } catch (XPatherException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (token == null) { return false; } // DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpost = new HttpPost(LOGIN_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(USER_FIELD, login)); nvps.add(new BasicNameValuePair(PASS_FIELD, pw)); nvps.add(new BasicNameValuePair(REMEMBERME, "1")); nvps.add(new BasicNameValuePair("stage", "1")); nvps.add(new BasicNameValuePair("back_url", "/")); nvps.add(new BasicNameValuePair("token", token)); Log.d("token:", token); tokenField = token; if (cookieStore != null) { httpclient.setCookieStore(cookieStore); } try { httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); Header[] headers = response.getHeaders("Set-Cookie"); if (cookieStore.getCookies().size() < 2) { loginName = null; loginStatus = false; } else { loginName = login; loginStatus = true; cookieStore = httpclient.getCookieStore(); } if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return loginStatus; }
From source file:org.xdi.oxauth.dev.TestSessionWorkflow.java
@Parameters({ "userId", "userSecret", "clientId", "clientSecret", "redirectUri" }) @Test//from w w w .j a v a2 s .c o m public void test(final String userId, final String userSecret, final String clientId, final String clientSecret, final String redirectUri) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); try { CookieStore cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient); //////////////////////////////////////////////// // TV side. Code 1 // //////////////////////////////////////////////// AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null); authorizationRequest1.setAuthUsername(userId); authorizationRequest1.setAuthPassword(userSecret); authorizationRequest1.getPrompts().add(Prompt.NONE); authorizationRequest1.setState("af0ifjsldkj"); authorizationRequest1.setRequestSessionId(true); AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint); authorizeClient1.setRequest(authorizationRequest1); AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor); // showClient(authorizeClient1, cookieStore); String code1 = authorizationResponse1.getCode(); String sessionId = authorizationResponse1.getSessionId(); Assert.assertNotNull("code1 is null", code1); Assert.assertNotNull("sessionId is null", sessionId); // TV sends the code to the Backend // We don't use httpClient and cookieStore during this call //////////////////////////////////////////////// // Backend 1 side. Code 1 // //////////////////////////////////////////////// // Get the access token TokenClient tokenClient1 = new TokenClient(tokenEndpoint); TokenResponse tokenResponse1 = tokenClient1.execAuthorizationCode(code1, redirectUri, clientId, clientSecret); String accessToken1 = tokenResponse1.getAccessToken(); Assert.assertNotNull("accessToken1 is null", accessToken1); // Get the user's claims UserInfoClient userInfoClient1 = new UserInfoClient(userInfoEndpoint); UserInfoResponse userInfoResponse1 = userInfoClient1.execUserInfo(accessToken1); Assert.assertTrue("userInfoResponse1.getStatus() is not 200", userInfoResponse1.getStatus() == 200); // System.out.println(userInfoResponse1.getEntity()); //////////////////////////////////////////////// // TV side. Code 2 // //////////////////////////////////////////////// AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null); authorizationRequest2.getPrompts().add(Prompt.NONE); authorizationRequest2.setState("af0ifjsldkj"); authorizationRequest2.setSessionId(sessionId); AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint); authorizeClient2.setRequest(authorizationRequest2); AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor); // showClient(authorizeClient2, cookieStore); String code2 = authorizationResponse2.getCode(); Assert.assertNotNull("code2 is null", code2); // TV sends the code to the Backend // We don't use httpClient and cookieStore during this call //////////////////////////////////////////////// // Backend 2 side. Code 2 // //////////////////////////////////////////////// // Get the access token TokenClient tokenClient2 = new TokenClient(tokenEndpoint); TokenResponse tokenResponse2 = tokenClient2.execAuthorizationCode(code2, redirectUri, clientId, clientSecret); String accessToken2 = tokenResponse2.getAccessToken(); Assert.assertNotNull("accessToken2 is null", accessToken2); // Get the user's claims UserInfoClient userInfoClient2 = new UserInfoClient(userInfoEndpoint); UserInfoResponse userInfoResponse2 = userInfoClient2.execUserInfo(accessToken2); Assert.assertTrue("userInfoResponse1.getStatus() is not 200", userInfoResponse2.getStatus() == 200); // System.out.println(userInfoResponse2.getEntity()); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } }
From source file:net.bither.http.BaseHttpResponse.java
private void setCookieStore(DefaultHttpClient httpClient) { if (getHttpType() != HttpType.OtherApi) { if (getHttpType() == HttpType.GetBitherCookie || getUrl().contains(BitherUrl.BITHER_DNS.BITHER_USER_DOMAIN)) { httpClient.setCookieStore(PersistentCookieStore.getInstance()); } else {/* w ww . j a v a 2s .c om*/ if (getUrl().contains(BitherUrl.BITHER_DNS.BITHER_BITCOIN_DOMAIN)) { httpClient.setCookieStore(getCookieStore(BitherUrl.BITHER_DNS.BITHER_BITCOIN_DOMAIN)); } if (getUrl().contains(BitherUrl.BITHER_DNS.BITHER_STATS_DOMAIN)) { httpClient.setCookieStore(getCookieStore(BitherUrl.BITHER_DNS.BITHER_STATS_DOMAIN)); } } } }
From source file:com.jelastic.JelasticService.java
private DefaultHttpClient getHttpClient() { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient = wrapClient(httpclient); httpclient.setCookieStore(getCookieStore()); return httpclient; }
From source file:org.mobisocial.corral.CorralTicketProvider.java
public void putACL(String objName, MIdentity[] buddies) throws ClientProtocolException, IOException { if (SERVER_URL == null) { Log.w(TAG, "no file upload service"); return;/*from w ww . ja va2 s . c o m*/ } Log.d(TAG, "---Start to Put ACL---"); int i = 0; String[] ident = new String[buddies.length]; for (MIdentity buddy : buddies) { ident[i] = getShortIdentity(buddy); i++; } String shortidentity = getShortIdentity(mIdentitiesManager.getMyDefaultIdentity()); String url = SERVER_URL + "user/" + shortidentity + "/object/" + objName + "/update-acl/"; // Set up HTTP request DefaultHttpClient http = new CertifiedHttpClient(mContext); http.setCookieStore(cookieStore); HttpPost httppost = new HttpPost(url); String postdata = ""; for (MIdentity buddy : buddies) { String si = getShortIdentity(buddy); if (si != null) { if (postdata.length() > 0) { postdata += ","; } postdata += si; } } List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1); nameValuePair.add(new BasicNameValuePair("identities", postdata)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); HttpResponse response = http.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Failed to post ACL. StatusCode:" + response.getStatusLine().getStatusCode()); } }
From source file:org.xdi.oxauth.interop.SupportClaimsRequestSpecifyingSubValue.java
@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "hostnameVerifier" }) @Test//from ww w. j a v a 2s. c o m public void supportClaimsRequestSpecifyingSubValueFail(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 (fail)"); 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); // 2. Request authorization List<String> scopes = Arrays.asList("openid", "email"); String nonce = UUID.randomUUID().toString(); String state = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce); authorizationRequest.setAuthUsername(userId); authorizationRequest.setAuthPassword(userSecret); authorizationRequest.getPrompts().add(Prompt.NONE); authorizationRequest.setState(state); JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, 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(); authorizationRequest.setRequest(authJwt); AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint); authorizeClient.setRequest(authorizationRequest); AuthorizationResponse authorizationResponse = authorizeClient.exec(); showClient(authorizeClient); assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus()); assertNotNull(authorizationResponse.getErrorType(), "The error type is null"); assertEquals(authorizationResponse.getErrorType(), AuthorizeErrorResponseType.USER_MISMATCHED); assertNotNull(authorizationResponse.getErrorDescription(), "The error description is null"); }
From source file:messenger.PlurkApi.java
public String logout() { PlurkApi p = PlurkApi.getInstance(); if (cookiestore == null) p.login();// ww w . ja v a2 s. c o m 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 { HttpGet httpget = new HttpGet(getApiUri("/Users/logout?" + "api_key=" + API_KEY)); 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; }