List of usage examples for org.apache.http.client CookieStore addCookie
void addCookie(Cookie cookie);
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 {/* w w w . j a v a 2s . c om*/ 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:bear.plugins.java.JenkinsCache.java
public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {// w w w . j a va 2 s. 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:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java
private static CookieStore handleCsrfCookies(CookieStore cookieStore) { List<Cookie> cookies = new ArrayList<Cookie>(); for (Cookie cookie : cookieStore.getCookies()) { if (!cookie.getName().contains("CSRF")) { cookies.add(cookie);// w w w. j a v a 2 s.co m } } cookieStore.clear(); for (Cookie cookie : cookies) { cookieStore.addCookie(cookie); } return cookieStore; }
From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java
public static String processSSOCookie(CookieStore cookieStore, String serverA, String serverB) { String ssoID = null;//from w w w. j a va 2 s .c o m for (Cookie cookie : cookieStore.getCookies()) { if ("JSESSIONIDSSO".equalsIgnoreCase(cookie.getName())) { ssoID = cookie.getValue(); if (serverA.equals(serverB) == false) { // Make an sso cookie to send to serverB Cookie copy = copyCookie(cookie, serverB); cookieStore.addCookie(copy); } } } assertTrue("Didn't saw JSESSIONIDSSO", ssoID != null); return ssoID; }
From source file:edu.mit.scratch.Scratch.java
public static List<ScratchUser> getUsers(final int limit, final int offset) throws ScratchUserException { if ((offset < 0) || (limit < 0)) throw new ScratchUserException(); final List<ScratchUser> users = new ArrayList<>(); try {//from www. j a v a 2s . c om final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); lang.setPath("/"); lang.setDomain(".scratch.mit.edu"); cookieStore.addCookie(lang); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://scratch.mit.edu/api/v1/user/?format=json&limit=" + limit + "&offset=" + offset) .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu").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").build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchUserException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ = new JSONObject(result.toString().trim()); final Iterator<?> keys = jsonOBJ.keys(); while (keys.hasNext()) { final String key = "" + keys.next(); final Object o = jsonOBJ.get(key); final String val = "" + o; if (key.equals("objects")) { final JSONArray jsonArray = (JSONArray) o; for (int i = 0; i < jsonArray.length(); i++) { final JSONObject jsonOBJ2 = jsonArray.getJSONObject(i); users.add(new ScratchUser("" + jsonOBJ2.get("username"))); } } } return users; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); throw new ScratchUserException(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } }
From source file:net.paissad.minus.utils.HttpClientUtils.java
/** * /*from w w w.j ava 2 s . c o m*/ * @param baseURL * @param parametersBody * @param sessionId * @param fileToUpload - The file to upload. * @param filename - The name of the file to use during the upload process. * @return The response received from the Minus API. * @throws MinusException */ public static MinusHttpResponse doUpload(final String baseURL, final Map<String, String> parametersBody, final String sessionId, final File fileToUpload, final String filename) throws MinusException { DefaultHttpClient client = null; HttpPost uploadRequest = null; InputStream responseContent = null; try { String url = baseURL; if (parametersBody != null && !parametersBody.isEmpty()) { url += CommonUtils.encodeParams(parametersBody); } uploadRequest = new HttpPost(url); client = new DefaultHttpClient(); client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler()); FileEntity fileEntity = new FileEntity(fileToUpload, "application/octet-stream"); uploadRequest.setEntity(fileEntity); // We add this headers as specified by the Minus.com API during file // upload. uploadRequest.addHeader("Content-Disposition", "attachment; filename=a.bin"); uploadRequest.addHeader("Content-Type", "application/octet-stream"); 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(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse httpResponse = client.execute(uploadRequest); // 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; } } StringBuilder result = new StringBuilder(); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity respEntity = httpResponse.getEntity(); if (respEntity != null) { result.append(EntityUtils.toString(respEntity)); EntityUtils.consume(respEntity); } } else { // The response code is not OK. StringBuilder errMsg = new StringBuilder(); errMsg.append(" Upload failed => ").append(httpResponse.getStatusLine()); if (uploadRequest != null) { errMsg.append(" : ").append(uploadRequest.getURI()); } throw new MinusException(errMsg.toString()); } return new MinusHttpResponse(result.toString(), sessionCookie); } catch (Exception e) { if (uploadRequest != null) { uploadRequest.abort(); } String errMsg = "Error while uploading file (" + fileToUpload + ") : " + e.getMessage(); throw new MinusException(errMsg, e); } finally { if (client != null) { client.getConnectionManager().shutdown(); } CommonUtils.closeAllStreamsQuietly(responseContent); } }
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.//from w ww . j a va 2 s. com * * @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:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static void addCookie(CookieStore cookieStore, String domain, String name, String value, String path, String charset) {/*from w w w . j a v a 2 s . c o m*/ if (ReqRspUtil.needEncoding(name, false)) name = ReqRspUtil.encode(name, charset); if (ReqRspUtil.needEncoding(value, false)) value = ReqRspUtil.encode(value, charset); BasicClientCookie cookie = new BasicClientCookie(name, value); if (!StringUtil.isEmpty(domain, true)) cookie.setDomain(domain); if (!StringUtil.isEmpty(path, true)) cookie.setPath(path); cookieStore.addCookie(cookie); }
From source file:sand.actionhandler.weibo.UdaClient.java
public static void addCookie(CookieStore cookieStore) { // HttpClient Cookie,? // ?cookie// w w w . j av a2s . co m BasicClientCookie cookie = new BasicClientCookie("SINAGLOBAL", "4384152551131.761.1366874745139"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); cookie = new BasicClientCookie("ULV", "1366874745145:1:1:1:4384152551131.761.1366874745139:"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); cookie = new BasicClientCookie("ALF", "1369466789"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); cookie = new BasicClientCookie("un", "tarzon@21cn.com"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); cookie = new BasicClientCookie("SUE", "es%3D888879b5c6579ed58ce44764fc70789a%26ev%3Dv1%26es2%3Dea414c75258d739dc29dac83a32e13d7%26rs0%3D0Pfpg7NGhPKa7WCtgXEyb7rf8eycrrUksec83xOU6kkZfPW7NSVM01dl0YwSxn5Yg5qgCFI4CTJdZCaUdS1xI7GO%252BOiXaUVZo6XI3DZMBslgxtYYLiA5ho8BwzAzaj5N4mHmd6yubMcNRiEK49TmeQ2BsQKujgfqRIh4i3Qc27c%253D%26rv%3D0"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); cookie = new BasicClientCookie("SUP", "cv%3D1%26bt%3D1366943072%26et%3D1366944871%26d%3Dc909%26i%3D957b%26us%3D1%26vf%3D0%26vt%3D0%26ac%3D2%26st%3D0%26uid%3D1694607674%26user%3Dtarzon%254021cn.com%26ag%3D4%26name%3Dtarzon%254021cn.com%26nick%3Dtarzon%26fmp%3D%26lcp%3D2013-02-27%252014%253A02%253A16"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); cookie = new BasicClientCookie("SUS", "SID-1694607674-1366943072-JA-4hcq3-2172dd350b7313b3544937abc38f3e72"); //cookie.setVersion(0); // cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); }
From source file:com.android.fastlibrary.volley.VolleyHelper.java
/** * cookie//from ww w .j a v a 2 s .co m * <p/> * cookie? * setCookie(); */ public void setCookie() { CookieStore cs = httpClient.getCookieStore(); cs.addCookie(new BasicClientCookie2("cookie", "spooky")); }