List of usage examples for org.apache.http.client CookieStore getCookies
List<Cookie> getCookies();
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession createSession(final String username, String password) throws ScratchLoginException { try {//from w ww . j a v a 2 s. c om final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/") .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu") .addHeader("X-Requested-With", "XMLHttpRequest").build(); resp = httpClient.execute(csrf); resp.close(); String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); final JSONObject loginObj = new JSONObject(); loginObj.put("username", username); loginObj.put("password", password); loginObj.put("captcha_challenge", ""); loginObj.put("captcha_response", ""); loginObj.put("embed_captcha", false); loginObj.put("timezone", "America/New_York"); loginObj.put("csrfmiddlewaretoken", csrfToken); final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build(); resp = httpClient.execute(login); password = null; 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); final JSONObject jsonOBJ = new JSONObject( result.toString().substring(1, result.toString().length() - 1)); if ((int) jsonOBJ.get("success") != 1) throw new ScratchLoginException(); String ssi = null; String sct = null; String e = null; final Header[] headers = resp.getAllHeaders(); for (final Header header : headers) if (header.getName().equals("Set-Cookie")) { final String value = header.getValue(); final String[] split = value.split(Pattern.quote("; ")); for (final String s : split) { if (s.contains("=")) { final String[] split2 = s.split(Pattern.quote("=")); final String key = split2[0]; final String val = split2[1]; if (key.equals("scratchsessionsid")) ssi = val; else if (key.equals("scratchcsrftoken")) sct = val; else if (key.equals("expires")) e = val; } } } resp.close(); return new ScratchSession(ssi, sct, e, username); } catch (final IOException e) { e.printStackTrace(); throw new ScratchLoginException(); } }
From source file:com.ntsync.android.sync.client.NetworkUtilities.java
/** * CookieStore per AccountName to prevent mixing of the sessions. * //from ww w . j ava 2 s .c o m * @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.exoplatform.shareextension.service.UploadAction.java
@Override protected boolean doExecute() { String id = uploadInfo.uploadId; String boundary = "----------------------------" + id; String CRLF = "\r\n"; int status = -1; OutputStream output = null;/*from w w w .j ava2 s . co m*/ PrintWriter writer = null; try { // Open a connection to the upload web service StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal") .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id); URL uploadUrl = new URL(stringUrl.toString()); HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection(); uploadReq.setDoOutput(true); uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Pass the session cookies for authentication CookieStore store = ExoConnectionUtils.cookiesStore; if (store != null) { StringBuffer cookieString = new StringBuffer(); for (Cookie cookie : store.getCookies()) { cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "); } uploadReq.addRequestProperty("Cookie", cookieString.toString()); } ExoConnectionUtils.setUserAgent(uploadReq); // Write the form data output = uploadReq.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadInfo.fileToUpload.documentName + "\"").append(CRLF); writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF); writer.append(CRLF).flush(); byte[] buf = new byte[1024]; while (uploadInfo.fileToUpload.documentData.read(buf) != -1) { output.write(buf); } output.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); // Execute the connection and retrieve the status code status = uploadReq.getResponseCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e); } finally { if (uploadInfo != null && uploadInfo.fileToUpload != null && uploadInfo.fileToUpload.documentData != null) try { uploadInfo.fileToUpload.documentData.close(); } catch (IOException e1) { Log.e(LOG_TAG, "Error while closing the upload stream", e1); } if (output != null) try { output.close(); } catch (IOException e) { Log.e(LOG_TAG, "Error while closing the connection", e); } if (writer != null) writer.close(); } if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) { // Exit if the upload went wrong return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName); } status = -1; try { // Prepare the request to save the file in JCR String stringUrl = postInfo.ownerAccount.serverUrl + "/portal" + ExoConstants.DOCUMENT_CONTROL_PATH_REST; Uri moveUri = Uri.parse(stringUrl); moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id) .appendQueryParameter("action", "save") .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace) .appendQueryParameter("driveName", uploadInfo.drive) .appendQueryParameter("currentFolder", uploadInfo.folder) .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build(); HttpGet moveReq = new HttpGet(moveUri.toString()); // Execute the request and retrieve the status code HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq); status = move.getStatusLine().getStatusCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e); } boolean ret = false; if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully"); } else { ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName); } return ret; }
From source file:eu.masconsult.bgbanking.utils.CookieQuotesFixerResponseInterceptor.java
@Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); for (Header header : response.getAllHeaders()) { if (!header.getName().equalsIgnoreCase("Set-Cookie")) { continue; }/* w w w . ja v a2 s .c om*/ Matcher matcher = pattern.matcher(header.getValue()); if (!matcher.find()) { continue; } for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equalsIgnoreCase(matcher.group(1))) { if (cookie instanceof BasicClientCookie) { ((BasicClientCookie) cookie).setValue('"' + cookie.getValue() + '"'); } else if (cookie instanceof BasicClientCookie2) { ((BasicClientCookie2) cookie).setValue('"' + cookie.getValue() + '"'); } else { Log.w(TAG, "unhandled cookie implementation " + cookie.getClass().getName()); } break; } } } }
From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthManager.java
/** * EGet the authenfication by executing the defined requests sequence. * * @throws IOException/* w w w . ja va2 s . c o m*/ * @throws ClientProtocolException */ public ExitStatus authentificate() throws ClientProtocolException, IOException { authCookie = null; if (firstRequest != null) { final CookieStore cookieStore = new BasicCookieStore(); client = HttpClients.custom().setDefaultCookieStore(cookieStore) .setRedirectStrategy(new LaxRedirectStrategy()).useSystemProperties().build(); lastResponse = firstRequest.executeSequence(client); final List<Cookie> cookies = cookieStore.getCookies(); final StringBuilder strBuff = new StringBuilder(); for (final Cookie cookie : cookies) { strBuff.append(cookie.getName()); strBuff.append("="); strBuff.append(cookie.getValue()); strBuff.append(";"); } authCookie = strBuff.toString(); } return ExitStatus.COMPLETED; }
From source file:com.appbase.androidquery.callback.AjaxStatus.java
/** * Return the cookies set by the server. * /*from www .j a v a 2s . c o m*/ * Return values only when source is not from cache (source == NETWORK), returns empty list otherwise. * * @return cookies */ public List<Cookie> getCookies() { if (context == null) return Collections.emptyList(); CookieStore store = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); if (store == null) return Collections.emptyList(); return store.getCookies(); }
From source file:com.benefit.buy.library.http.query.callback.AjaxStatus.java
/** * Return the cookies set by the server. Return values only when source is not from cache (source == NETWORK), * returns empty list otherwise.// w ww .jav a 2 s . com * @return cookies */ public List<Cookie> getCookies() { if (context == null) { return Collections.emptyList(); } CookieStore store = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); if (store == null) { return Collections.emptyList(); } return store.getCookies(); }
From source file:io.mandrel.requests.http.ApacheHttpRequester.java
public Blob extractWebPage(Uri uri, CloseableHttpResponse result, HttpContext localContext) throws MalformedURLException, IOException { try {//w w w. j a v a 2s . co m Map<String, List<String>> headers = new HashMap<String, List<String>>(); if (result.getAllHeaders() != null) { for (Header header : result.getAllHeaders()) { headers.put(header.getName(), Arrays.asList(header.getValue())); } } List<io.mandrel.requests.http.Cookie> cookies = null; if (localContext != null) { CookieStore store = (CookieStore) localContext.getAttribute(HttpClientContext.COOKIE_STORE); if (store.getCookies() != null) { cookies = store.getCookies().stream().filter(cookie -> cookie != null) .map(cookie -> new io.mandrel.requests.http.Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiryDate() != null ? cookie.getExpiryDate().getTime() : 0, cookie.getExpiryDate() != null ? (int) cookie.getExpiryDate().getTime() : 0, cookie.isSecure(), false)) .collect(Collectors.toList()); } } HttpFetchMetadata metadata = new HttpFetchMetadata().headers(headers).cookies(cookies); metadata.setUri(uri) .setStatusCode(result.getStatusLine() != null ? result.getStatusLine().getStatusCode() : 0) .setStatusText( result.getStatusLine() != null ? result.getStatusLine().getReasonPhrase() : null); HttpEntity entity = result.getEntity(); InputStream content = entity.getContent(); try { long contentLength = entity.getContentLength(); Blob blob = new Blob(new BlobMetadata().setUri(uri) .setSize(contentLength < 0 ? null : contentLength).setFetchMetadata(metadata)) .payload(IOUtils.toByteArray(content)); return blob; } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection release content.close(); } } finally { result.close(); } }
From source file:com.kynetx.api.java
protected void storeCookies(CookieStore toStore) throws IOException { if (isWritable()) { File path = new File(context.getExternalFilesDir(null), "cookies"); OutputStream output = new FileOutputStream(path); ObjectOutputStream oos = new ObjectOutputStream(output); List<Cookie> cookies = toStore.getCookies(); oos.writeInt(cookies.size());/*from www. ja va 2 s . c o m*/ for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); oos.writeObject(cookie.getName()); oos.writeObject(cookie.getValue()); oos.writeObject(cookie.getDomain()); oos.writeObject(cookie.getPath()); oos.writeInt(cookie.getVersion()); } oos.close(); } else { throw new IOException(); } }