List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:com.waitwha.nessus.server.Server.java
/** * Constructor/*from www. j ava2 s . co m*/ * * @param url End-point URL of the Nessus Server. (i.e. https://localhost:8834) */ public Server(final String url) { this.url = url; /* * Configure XML parsing. */ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { this.builder = factory.newDocumentBuilder(); log.finest(String.format("Successfully configured XML parsing using builder: %s", this.builder.getClass().getName())); } catch (ParserConfigurationException e) { log.warning(String.format("Could not configure XML parsing: %s", e.getMessage())); } /* * Setup SSL for HttpClient configurations. Here we will configure SSL/TLS to * accept all hosts (no verification on certificates). This is because Nessus by * default used a self-generate CA and certificate for the servers. So, a simple * self-signed-strategy will not work as we are not dealing with strictly * self-signed certs, but ones generated and signed by a self-generated CA. * * TODO Perhaps the serial number of the CA is always the same so in the future we * could use a strategy to only accept certs by this one serial. * * See http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientConfiguration.java. * * TODO We need to work on the code here to be more up-to-date. SSLSocketFactory is deprecated, but * finding up-to-date docs on how to use SSLContext with a custom TrustStrategy and not using a KeyStore is * not currently available. */ //SSLContext sslContext = SSLContexts.createSystemDefault(); Registry<ConnectionSocketFactory> socketFactoryRegistry = null; try { socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLSocketFactory(new MyTrustStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); log.finest(String.format("Configured SSL/TLS connections for %s.", url)); } catch (Exception e) { log.warning( String.format("Could not configure SSL/TLS: %s %s", e.getClass().getName(), e.getMessage())); } SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); this.connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); this.connectionManager.setSocketConfig(socketConfig); log.finest(String.format("Configured socket connections for %s.", url)); this.cookieStore = new BasicCookieStore() { private static final long serialVersionUID = 1L; /** * @see org.apache.http.impl.client.BasicCookieStore#addCookie(org.apache.http.cookie.Cookie) */ @Override public synchronized void addCookie(Cookie cookie) { log.finest(String.format("[%s] Cookie added: %s=%s", url, cookie.getName(), cookie.getValue())); super.addCookie(cookie); } }; log.finest(String.format("Configured default/basic cookie storage for connections to %s", url)); }
From source file:zz.pseas.ghost.client.GhostClient.java
public void addCookie(String k, String v) { BasicClientCookie cookie = new BasicClientCookie(k, v); cookie.setDomain(".taobao.com"); CookieStore cookieStore = context.getCookieStore(); if (cookieStore == null) { context.setCookieStore(new BasicCookieStore()); }// ww w. j a v a2 s . co m context.getCookieStore().addCookie((Cookie) cookie); }
From source file:com.vmware.bdd.plugin.clouderamgr.poller.host.HostInstallPoller.java
private void login() throws Exception { cookieStore = new BasicCookieStore(); CloseableHttpClient loginClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); URI uri = new URI(domain + POST_ADDR); HttpUriRequest login = RequestBuilder.post().setUri(uri).addParameter(POST_USER_KEY, username) .addParameter(POST_PASSWORD_KEY, password).build(); logger.info("Login " + uri.toString()); CloseableHttpResponse response = loginClient.execute(login); try {/*from ww w . j av a 2 s .com*/ HttpEntity entity = response.getEntity(); logger.info("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { logger.info("Get no cookies"); } else { logger.info("All cookies: " + (new Gson()).toJson(cookies)); } } finally { response.close(); loginClient.close(); } }
From source file:org.everit.authentication.http.session.ecm.tests.SessionAuthenticationComponentTest.java
@Test @TestDuringDevelopment/*from w ww . j av a 2s. co m*/ public void testAccessHelloPage() throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); long sessionResourceId = hello(httpContext, authenticationContext.getDefaultResourceId()); sessionResourceId = hello(httpContext, sessionResourceId); sessionResourceId = hello(httpContext, sessionResourceId); logoutPost(httpContext); sessionResourceId = hello(httpContext, authenticationContext.getDefaultResourceId()); sessionResourceId = hello(httpContext, sessionResourceId); hello(httpContext, sessionResourceId); logoutGet(httpContext); hello(httpContext, authenticationContext.getDefaultResourceId()); }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ApiStoreExecutor.java
/** * Update the APIM DB for the published API. * /*from w ww . j a v a 2s. c o m*/ * @param service * @param serviceName */ private void publishDataToAPIM(Service service, String serviceName) { if (apimEndpoint == null || apimUsername == null || apimPassword == null) { String msg = "APIManager endpoint URL or credentials are not defined"; log.error(msg); throw new RuntimeException(msg + "API Publish might fail"); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); authenticateAPIM(httpContext); String addAPIendpoint = apimEndpoint + "publisher/site/blocks/item-add/ajax/add.jag"; try { // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(addAPIendpoint); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(); if (service.getAttachedEndpoints().length == 0) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore.Publishing at gateway might fail"; log.warn(msg); } if (service.getAttachedEndpoints().length > 0) { params.add(new BasicNameValuePair(API_ENDPOINT, service.getAttachedEndpoints()[0].getUrl())); } params.add(new BasicNameValuePair(API_ACTION, API_ADD_ACTION)); params.add(new BasicNameValuePair(API_NAME, serviceName)); params.add(new BasicNameValuePair(API_CONTEXT, serviceName)); params.add(new BasicNameValuePair(API_VERSION, service.getAttribute(SERVICE_VERSION))); params.add(new BasicNameValuePair("API_PROVIDER", CarbonContext.getThreadLocalCarbonContext().getUsername())); params.add(new BasicNameValuePair(API_TIER, defaultTier)); params.add(new BasicNameValuePair(API_URI_PATTERN, DEFAULT_URI_PATTERN)); params.add(new BasicNameValuePair(API_URI_HTTP_METHOD, DEFAULT_HTTP_VERB)); params.add(new BasicNameValuePair(API_URI_AUTH_TYPE, DEFAULT_AUTH_TYPE)); params.add(new BasicNameValuePair(API_VISIBLITY, DEFAULT_VISIBILITY)); params.add(new BasicNameValuePair(API_THROTTLING_TIER, apiThrottlingTier)); for (int i = 0; i < service.getAttachedWsdls().length; i++) { String wsdlPath = service.getAttachedWsdls()[0].getPath(); if (wsdlPath != null && wsdlPath.toLowerCase().startsWith("http")) { params.add(new BasicNameValuePair(API_WSDL, wsdlPath)); } } httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(httppost, httpContext); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } } catch (Exception e) { log.error("Error in updating APIM DB", e); } // after publishing update the lifecycle status //updateStatus(service, serviceName, httpContext); }
From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java
private int readWrite(HttpEntityEnclosingRequestBase request) { Log.v(TAG, "readWrite"); CookieStore mCookieStore = new BasicCookieStore(); mCookieStore.addCookie(mAuthCookie); DefaultHttpClient httpClient = new DefaultHttpClient(); BasicHttpContext mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); // Encode request body. StringEntity requestEntity;/*from w w w .j ava2s . com*/ try { requestEntity = new StringEntity(encode(mRequestBody)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "HTTP encoding failed=" + e); return mStatusCode; } try { final HttpParams getParams = new BasicHttpParams(); HttpClientParams.setRedirecting(getParams, false); request.setParams(getParams); request.setHeader("Content-Type", getMimeType()); request.setEntity(requestEntity); HttpResponse response = httpClient.execute(request, mHttpContext); Log.d(TAG, "status=" + response.getStatusLine()); // Read response body. HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { InputStream is = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } is.close(); mStatusCode = response.getStatusLine().getStatusCode(); mStatusReason = response.getStatusLine().getReasonPhrase(); if (mStatusCode == 200) { mResponseBody = decode(sb.toString()); Log.v(TAG, "mResponseBody=" + sb.toString()); } return mStatusCode; } } catch (IOException e) { Log.e(TAG, "exception=" + e); Log.e(TAG, Log.getStackTraceString(e)); } finally { httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } return mStatusCode; }
From source file:com.kynetx.api.java
public void clearCookies() { cookieStore = null;/* w ww . ja v a 2 s. c o m*/ try { storeCookies(new BasicCookieStore()); } catch (IOException e) { // TODO Auto-generated catch block } }
From source file:io.undertow.servlet.test.session.ServletURLRewritingSessionTestCase.java
@Test public void testURLRewritingWithExistingOldSessionIdAndOtherPathParams() throws IOException { TestHttpClient client = new TestHttpClient(); client.setCookieStore(new BasicCookieStore()); try {//w w w.j a v a 2 s.c om HttpGet get = new HttpGet( DefaultServer.getDefaultServerURL() + "/servletContext/foo;jsessionid=foobar&a=b"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); String url = HttpClientUtils.readResponse(result); Header[] header = result.getHeaders(COUNT); Assert.assertEquals("0", header[0].getValue()); get = new HttpGet(url); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); url = HttpClientUtils.readResponse(result); header = result.getHeaders(COUNT); Assert.assertEquals("1", header[0].getValue()); get = new HttpGet(url); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); url = HttpClientUtils.readResponse(result); header = result.getHeaders(COUNT); Assert.assertEquals("2", header[0].getValue()); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.ofbiz.testtools.seleniumxml.RemoteRequest.java
public void runTest() { ClientConnectionManager ccm = new ThreadSafeClientConnManager(defaultParameters, supportedSchemes); // new SingleClientConnManager(getParams(), supportedSchemes); DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters); client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); ///* w w w . ja va2 s. co m*/ // We first try to login with the loginAs to set the session. // Then we call the remote service. // HttpEntity entity = null; ResponseHandler<String> responseHandler = null; try { BasicHttpContext localContext = new BasicHttpContext(); // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); Header sessionHeader = null; if (this.loginAsUrl != null) { String loginAsUri = this.host + this.loginAsUrl; String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam; HttpGet req2 = new HttpGet(loginAsUri + loginAsParamString); System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString); req2.setHeader("Connection", "Keep-Alive"); HttpResponse rsp = client.execute(req2, localContext); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header hdr = headers[i]; String headerValue = hdr.getValue(); if (headerValue.startsWith("JSESSIONID")) { sessionHeader = hdr; } System.out.println("login: " + hdr.getName() + " : " + hdr.getValue()); } List<Cookie> cookies = cookieStore.getCookies(); System.out.println("cookies.size(): " + cookies.size()); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie(0): " + cookies.get(i)); } } //String paramString2 = "USERNAME=" + this.parent.getUserName() // + "&PASSWORD=" + this.parent.getPassword(); //String thisUri2 = this.host + "/eng/control/login?" + paramString2; //HttpGet req2 = new HttpGet ( thisUri2 ); //req2.setHeader("Connection","Keep-Alive"); //HttpResponse rsp = client.execute(req2, localContext); //Header sessionHeader = null; //Header[] headers = rsp.getAllHeaders(); //for (int i=0; i<headers.length; i++) { // Header hdr = headers[i]; // String headerValue = hdr.getValue(); // if (headerValue.startsWith("JSESSIONID")) { // sessionHeader = hdr; // } // System.out.println(headers[i]); // System.out.println(hdr.getName() + " : " + hdr.getValue()); //} //List<Cookie> cookies = cookieStore.getCookies(); //System.out.println("cookies.size(): " + cookies.size()); //for (int i = 0; i < cookies.size(); i++) { // System.out.println("Local cookie(0): " + cookies.get(i)); //} if (HttpHandleMode.equals(this.responseHandlerMode)) { } else { responseHandler = new JsonResponseHandler(this); } String paramString = urlEncodeArgs(this.inMap, false); String thisUri = null; if (sessionHeader != null) { String sessionHeaderValue = sessionHeader.getValue(); int pos1 = sessionHeaderValue.indexOf("="); int pos2 = sessionHeaderValue.indexOf(";"); String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; } else { thisUri = this.host + this.requestUrl + "?" + paramString; } //String sessionHeaderValue = sessionHeader.getValue(); //int pos1 = sessionHeaderValue.indexOf("="); //int pos2 = sessionHeaderValue.indexOf(";"); //String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); //System.out.println("sessionId: " + sessionId); //String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; //String thisUri = this.host + this.requestUrl + "?" + paramString; System.out.println("thisUri: " + thisUri); HttpGet req = new HttpGet(thisUri); if (sessionHeader != null) { req.setHeader(sessionHeader); } String responseBody = client.execute(req, responseHandler, localContext); /* entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i=0; i<headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(rsp.getEntity())); } */ } catch (HttpResponseException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } finally { // If we could be sure that the stream of the entity has been // closed, we wouldn't need this code to release the connection. // However, EntityUtils.toString(...) can throw an exception. // if there is no entity, the connection is already released try { if (entity != null) entity.consumeContent(); // release connection gracefully } catch (IOException e) { System.out.println("in 'finally' " + e.getMessage()); } } return; }
From source file:edu.mit.scratch.ScratchProject.java
public void setLoved(final ScratchSession session, final boolean loved) throws ScratchProjectException { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang);/*from ww w .ja v a 2s . c o m*/ cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)" + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36") .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.put() .setUri("https://scratch.mit.edu/site-api/users/lovers/" + this.getProjectID() + "/" + (loved ? "add" : "remove") + "/?usernames=" + session.getUsername()) .addHeader("Accept", "application/json, text/javascript, */*; q=0.01").addHeader("DNT", "1") .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/") .addHeader("Origin", "https://scratch.mit.edu/").addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("Cookie", "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken=" + session.getCSRFToken()) .addHeader("X-CSRFToken", session.getCSRFToken()).build(); try { resp = httpClient.execute(update); if (resp.getStatusLine().getStatusCode() != 200) throw new ScratchProjectException(); final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } }