List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:it.fabaris.wfp.application.Collect.java
/** * Shared HttpContext so a user doesn't have to re-enter login information * @return// w ww .ja v a2 s .c om */ public synchronized HttpContext getHttpContext() { if (localContext == null) { /** * set up one context for all HTTP requests so that authentication * and cookies can be retained. */ localContext = new SyncBasicHttpContext(new BasicHttpContext()); /** * establish a local cookie store for this attempt at downloading... */ CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); /** * and establish a credentials provider. Default is 7 minutes. * CredentialsProvider credsProvider = new AgingCredentialsProvider(7 * 60 * 1000); * localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider); */ } return localContext; }
From source file:sample.ui.mvc.MessageController.java
private String getBidMima(String bidId) { // bidId = "346"; String url = "http://wujinsuo.cn/index.php?ctl=deal&id=" + bidId + "&act=bid"; String mima = ""; try {/* w w w. j av a 2 s . c om*/ BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); doLogin(cookieStore, httpclient, ZHANGDAIYIXIAN); HttpGet httpget = new HttpGet(url); httpget.addHeader("Accept", ACCEPT); httpget.addHeader("User-Agent", AGENT); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String resultString = httpclient.execute(httpget, responseHandler); int index = resultString.indexOf("#mima\").val())!="); mima = resultString.substring(index + 16, index + 20); logger.info(mima); } catch (Exception e) { e.printStackTrace(); } return mima; }
From source file:fr.ippon.wip.http.hc.HttpClientResourceManager.java
private CookieStore getCookieStore(PortletRequest request) { String userSessionId = request.getPortletSession().getId(); CookieStore store;//from w w w . j ava2 s .c om synchronized (perUserCookieStoreMap) { store = perUserCookieStoreMap.get(userSessionId); if (store == null) { store = new BasicCookieStore(); perUserCookieStoreMap.put(userSessionId, store); } } return store; }
From source file:com.tri_voltage.md.io.YoutubeVideoParser.java
private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable { log.fine("Retrieving " + videoId); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("video_id", videoId)); qparams.add(new BasicNameValuePair("fmt", "" + format)); URI uri = getUri("get_video_info", qparams); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(uri); if (userAgent != null && userAgent.length() > 0) { httpget.setHeader("User-Agent", userAgent); }//from w w w . j ava2 s . c o m log.finer("Executing " + uri); HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == 200) { InputStream instream = entity.getContent(); String videoInfo = getStringFromInputStream(encoding, instream); if (videoInfo != null && videoInfo.length() > 0) { List<NameValuePair> infoMap = new ArrayList<NameValuePair>(); URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding); String downloadUrl = null; String filename = videoId; for (NameValuePair pair : infoMap) { String key = pair.getName(); String val = pair.getValue(); log.finest(key + "=" + val); if (key.equals("title")) { filename = val; } else if (key.equals("fmt_url_map")) { String[] formats = commaPattern.split(val); boolean found = false; for (String fmt : formats) { String[] fmtPieces = pipePattern.split(fmt); if (fmtPieces.length == 2) { int pieceFormat = Integer.parseInt(fmtPieces[0]); log.fine("Available format=" + pieceFormat); if (pieceFormat == format) { // found what we want downloadUrl = fmtPieces[1]; found = true; break; } } } if (!found) { log.warning( "Could not find video matching specified format, however some formats of the video do exist (use -verbose)."); } } } filename = cleanFilename(filename); if (filename.length() == 0) { filename = videoId; } else { filename += "_" + videoId; } filename += "." + extension; File outputfile = new File(outputdir, filename); if (downloadUrl != null) { downloadWithHttpClient(userAgent, downloadUrl, outputfile); } else { log.severe("Could not find video"); } } else { log.severe("Did not receive content from youtube"); } } else { log.severe("Could not contact youtube: " + response.getStatusLine()); } }
From source file:com.datatorrent.stram.util.WebServicesClient.java
public WebServicesClient(ClientConfig config) { if (SecurityUtils.isHadoopWebSecurityEnabled()) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager(connectionManager); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry); ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(), new BasicCookieStore(), false); client = new Client(httpClientHandler, config); } else {/*w w w .j a v a2 s .c om*/ client = Client.create(config); } }
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); }/*from w w w . j a va 2 s .c om*/ } } }; 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; }
From source file:net.paissad.minus.utils.HttpClientUtils.java
/** * Convenience method for sending HTTP requests. * <b><span style="color:red">Note</span></b>: This method is intended to be * used internally, not by end-users.// www. ja v a 2s . c om * * @param baseURL - <b>Example</b>: http://minus.com/api * @param parametersBody - The parameters (name => value pairs) to pass to * the request. * @param sessionId - If <tt>null</tt> or empty, then create and use a new * session, otherwise, use the specified session_id (which is * stored in a cookie). * @param requestType * @param additionalRequestHeaders - * @param expectedResponseType * @return The response retrieved from Minus API. * @throws MinusException */ private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody, final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders, final ExpectedResponseType expectedResponseType) throws MinusException { DefaultHttpClient client = null; HttpRequestBase request = null; InputStream responseContent = null; boolean errorOccured = false; try { if (requestType == RequestType.GET) { request = new HttpGet(baseURL); if (parametersBody != null && !parametersBody.isEmpty()) { request = appendParametersToRequest(request, parametersBody); } } else if (requestType == RequestType.POST) { UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody), HTTP.UTF_8); request = new HttpPost(baseURL); ((HttpPost) request).setEntity(encodedEntity); } else { throw new MinusException("The method (" + requestType + ") is unknown, weird ..."); } request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT)); if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) { for (Header aHeader : additionalRequestHeaders) { request.addHeader(aHeader); } } client = new DefaultHttpClient(); client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler()); client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); CookieStore cookieStore = new BasicCookieStore(); Cookie sessionCookie = null; if (sessionId != null && !sessionId.trim().isEmpty()) { sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId); ((BasicClientCookie2) sessionCookie).setPath("/"); ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME); ((BasicClientCookie2) sessionCookie).setVersion(0); cookieStore.addCookie(sessionCookie); } client.setCookieStore(cookieStore); HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // Execute the request ... pass local context as a parameter HttpResponse resp = client.execute(request, localContext); // Let's update the cookie have the name 'sessionid' for (Cookie aCookie : client.getCookieStore().getCookies()) { if (aCookie.getName().equals(MINUS_COOKIE_NAME)) { sessionCookie = aCookie; break; } } Object result = null; int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); if (entity != null) { if (expectedResponseType == ExpectedResponseType.STRING) { result = EntityUtils.toString(entity); EntityUtils.consume(entity); } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) { result = entity; } } } else { // The response code is not OK. StringBuilder errMsg = new StringBuilder(); errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine()); if (request != null) { errMsg.append(" : ").append(request.getURI()); } throw new MinusException(errMsg.toString()); } return new MinusHttpResponse(result, sessionCookie); } catch (Exception e) { errorOccured = true; if (request != null) { request.abort(); } String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage(); throw new MinusException(errMsg, e); } finally { if (client != null) { // We must not close the client is the expected response is an // InputStream. Indeed, if ever we close the client, we won't be // able to read the response because of SocketException. if (errorOccured) { client.getConnectionManager().shutdown(); } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) { client.getConnectionManager().shutdown(); } } CommonUtils.closeAllStreamsQuietly(responseContent); } }
From source file:com.ntsync.android.sync.client.NetworkUtilities.java
/** * CookieStore per AccountName to prevent mixing of the sessions. * // w w w . j a va2 s . c om * @param accountName * accountName or null (default) * @return */ private static HttpContext createHttpContext(String accountName, String authtoken) { BasicHttpContext ctx = new BasicHttpContext(); CookieStore store; synchronized (CL_LOCK) { store = COOKIES.get(accountName); if (store == null) { store = new BasicCookieStore(); COOKIES.put(accountName, store); } } ctx.setAttribute(ClientContext.COOKIE_STORE, store); if (authtoken != null) { boolean add = true; for (Cookie cookie : store.getCookies()) { if (COOKIE_SESSION_NAME.equals(cookie.getName())) { if (authtoken.equals(cookie.getValue())) { add = false; } break; } } if (add) { BasicClientCookie sessionCookie = new BasicClientCookie(COOKIE_SESSION_NAME, authtoken); sessionCookie.setSecure(true); store.addCookie(sessionCookie); } } return ctx; }
From source file:org.wso2.carbon.governance.registry.extensions.executors.APIDeleteExecutor.java
/** * Deletes API from the API Manager//from w ww . j a va 2 s . c o m * * @param api API Generic artifact. * @return True if successfully deleted. */ private boolean deleteFromAPIManager(GenericArtifact api) throws RegistryException { if (apimEndpoint == null || apimUsername == null || apimPassword == null) { throw new RuntimeException(ExecutorConstants.APIM_LOGIN_UNDEFINED); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); Utils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword); String removeEndpoint = apimEndpoint + ExecutorConstants.APIM_REMOVE_URL; try { // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(removeEndpoint); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(ExecutorConstants.API_ACTION, ExecutorConstants.API_REMOVE_ACTION)); params.add(new BasicNameValuePair(ExecutorConstants.API_NAME, api.getAttribute(ExecutorConstants.SERVICE_NAME))); params.add(new BasicNameValuePair(ExecutorConstants.API_PROVIDER, apimUsername)); params.add(new BasicNameValuePair(ExecutorConstants.API_VERSION, api.getAttribute(ExecutorConstants.SERVICE_VERSION))); httppost.setEntity(new UrlEncodedFormEntity(params, ExecutorConstants.DEFAULT_CHAR_ENCODING)); HttpResponse response = httpclient.execute(httppost, httpContext); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } } catch (ClientProtocolException e) { throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e); } catch (UnsupportedEncodingException e) { throw new RegistryException(ExecutorConstants.ENCODING_FAIL, e); } catch (IOException e) { throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e); } return true; }
From source file:org.sonatype.nexus.testsuite.security.SimpleSessionCookieIT.java
/** * Validate Nexus Cookies during Sign-in and Sign-out *//* w w w. j a v a 2 s.c o m*/ private void exerciseCookieSpec(final URL baseUrl) throws Exception { // handle cookies like a browser to aid validation final CookieSpec spec = new DefaultCookieSpecProvider().create(null); final CookieOrigin cookieOrigin = cookieOrigin(baseUrl); final CookieStore cookieStore = new BasicCookieStore(); final CredentialsProvider credProvider = credentialsProvider(); SetCookie loginCookie; try (CloseableHttpClient client = clientBuilder().setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credProvider).build()) { // 1. login with credentials and get session cookie // Set-Cookie: NXSESSIONID=98a766bc-bc33-4b3c-9d9f-d3bb85b0cf00; Path=/; Secure; HttpOnly HttpPost loginRequest = new HttpPost(resolveUrl(baseUrl, SESSION_PATH).toURI()); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", Strings2.encodeBase64(credentials().getUserPrincipal().getName()))); params.add(new BasicNameValuePair("password", Strings2.encodeBase64(credentials().getPassword()))); loginRequest.setEntity(new UrlEncodedFormEntity(params)); withCommonBrowserHeaders(loginRequest); try (CloseableHttpResponse response = client.execute(loginRequest, clientContext())) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat("login cookie should have been stored in the cookie store", cookieStore.getCookies(), hasSize(1)); assertThat("expected session cookie in cookie store", getSessionCookie(cookieStore), notNullValue()); Header[] setCookieHeaders = response.getHeaders(SET_COOKIE); Header sessionCookieHeader = getSessionCookieHeader(setCookieHeaders); List<Cookie> sessionCookies = spec.parse(sessionCookieHeader, cookieOrigin); loginCookie = (SetCookie) sessionCookies.get(0); String headerText = sessionCookieHeader.toString(); assertCommonSessionCookieAttributes(baseUrl, loginCookie, headerText); assertThat(String.format("expecting one cookie parsed from session %s header", SET_COOKIE), sessionCookies, hasSize(1)); assertThat(String.format( "expecting 2 %s headers for login, one session cookie, one remember me, but got %s", SET_COOKIE, setCookieHeaders), setCookieHeaders, arrayWithSize(2)); assertThat("login cookie should NOT look like deleteMe cookie", loginCookie.getValue(), not(containsString("deleteMe"))); assertThat( "login cookie should not have an expiry date - the UA deletes the session cookie when " + "replaced by a new one by same name from the server OR when the UA decides", loginCookie.isPersistent(), is(false)); assertThat("login session cookie with valid session id should always be marked HttpOnly", headerText, containsString("; HttpOnly")); } HttpClientContext logoutContext = HttpClientContext.create(); logoutContext.setCookieStore(cookieStore); HttpDelete logoutRequest = new HttpDelete(resolveUrl(baseUrl, SESSION_PATH).toURI()); withCommonBrowserHeaders(logoutRequest); // 2. Logout, sending valid session cookie, no credentials // Set-Cookie: NXSESSIONID=deleteMe; Path=/; Max-Age=0; Expires=Sun, 28-Dec-2014 15:59:11 GMT try (CloseableHttpResponse response = client.execute(logoutRequest, logoutContext)) { assertThat(response.getStatusLine().getStatusCode(), is(200)); // can't use client CookieStore to examine logout cookie, because the Expires header will prevent it from being // added but we can implicitly confirm it expired the existing cookie according to our client assertThat("logout cookie should have emptied the cookie store due to expiry date", cookieStore.getCookies(), hasSize(0)); Header[] setCookieHeaders = response.getHeaders(SET_COOKIE); Header sessionCookieHeader = getSessionCookieHeader(setCookieHeaders); List<Cookie> sessionCookies = spec.parse(sessionCookieHeader, cookieOrigin); SetCookie logoutCookie = (SetCookie) sessionCookies.get(0); final String headerText = sessionCookieHeader.toString(); assertCommonSessionCookieAttributes(baseUrl, logoutCookie, headerText); assertThat("expecting one cookie in same Set-Cookie header", sessionCookies, hasSize(1)); assertThat(String.format( "expecting 2 %s headers for logout, one session cookie delete cookie, one remember me delete cookie, but got %s", SET_COOKIE, setCookieHeaders), setCookieHeaders, arrayWithSize(2)); assertThat("logout session cookie value should be dummy value", logoutCookie.getValue(), equalTo("deleteMe")); assertThat("logout session cookie should be expired to tell browser to delete it", logoutCookie.isExpired(new Date()), is(true)); assertThat( "technically the presence of an expiry date means the cookie is persistent, but expiry will override", logoutCookie.isPersistent(), is(true)); assertThat( "logout cookie does not have a real session id value, therefore it does not need to be HttpOnly", headerText, not(containsString("; HttpOnly"))); } // 3. Access a protected resource again using our original login cookie, no credentials, to verify session is dead HttpGet loginFailedGet = new HttpGet(resolveUrl(baseUrl, PROTECTED_PATH).toURI()); cookieStore.addCookie(loginCookie); try (CloseableHttpResponse response = client.execute(loginFailedGet, HttpClientContext.create())) { assertThat("expected dead login session cookie to not authenticate", response.getStatusLine().getStatusCode(), is(401)); Header[] setCookieHeaders = response.getHeaders(SET_COOKIE); assertThat("expecting no session cookie since login was unsuccessful", getSessionCookieHeader(setCookieHeaders), nullValue()); assertThat("expecting no cookies since login was unsuccessful", setCookieHeaders, arrayWithSize(0)); } } }