List of usage examples for org.apache.http.client.protocol ClientContext COOKIE_STORE
String COOKIE_STORE
To view the source code for org.apache.http.client.protocol ClientContext COOKIE_STORE.
Click Source Link
From source file:com.vanda.beivandalibnetwork.utils.HttpUtils.java
/** * ? Cookie.//w w w . ja v a2 s . c o m * * @param context * ? * @return */ public static CookieStore getCookieStore(HttpContext context) { HttpContext ctx = context == null ? CURRENT_CONTEXT : context; return (CookieStore) (ctx == null ? null : ctx.getAttribute(ClientContext.COOKIE_STORE)); }
From source file:org.datacleaner.util.http.CASMonitorHttpClient.java
@Override public HttpResponse execute(final HttpUriRequest request) throws Exception { // enable cookies final CookieStore cookieStore = new BasicCookieStore(); final HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); _httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); final String ticketGrantingTicket; try {/*w ww. j a v a 2 s .com*/ ticketGrantingTicket = _ticketGrantingTicketRef.get(); } catch (IllegalStateException e) { if (e.getCause() instanceof SSLPeerUnverifiedException) { // Unverified SSL peer exceptions needs to be rethrown // specifically, since they can be caught and the user may // decide to remove certificate checks. throw (SSLPeerUnverifiedException) e.getCause(); } throw e; } final String ticket = getTicket(_requestedService, _casRestServiceUrl, ticketGrantingTicket, context); logger.debug("Got a service ticket: {}", ticketGrantingTicket); logger.debug("Cookies 2: {}", cookieStore.getCookies()); // now we request the spring security CAS check service, this will set // cookies on the client. final HttpGet cookieRequest = new HttpGet(_requestedService + "?ticket=" + ticket); final HttpResponse cookieResponse = executeHttpRequest(cookieRequest, context); EntityUtils.consume(cookieResponse.getEntity()); cookieRequest.releaseConnection(); logger.debug("Cookies 3: {}", cookieStore.getCookies()); final HttpResponse result = executeHttpRequest(request, context); logger.debug("Cookies 4: {}", cookieStore.getCookies()); return result; }
From source file:org.confab.PhpBB3Parser.java
/** * Constructs and submits a POST with the appropriate parameters to login to a vbulletin. * @param rootURL Base or root URL for the site to log into * @param username User's login name// w w w . j a v a2s. c om * @param password User's password * @return User object initialised with a HttpContext */ public User login(String rootURL, String username, String password) { Utilities.debug("login"); User ret = new User(username, password); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); try { // set up the POST HttpPost httppost = new HttpPost(rootURL + "login.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("do", "login")); nvps.add(new BasicNameValuePair("vb_login_username", username)); nvps.add(new BasicNameValuePair("vb_login_password", "")); nvps.add(new BasicNameValuePair("s", "")); nvps.add(new BasicNameValuePair("securitytoken", "guest")); nvps.add(new BasicNameValuePair("do", "login")); nvps.add(new BasicNameValuePair("vb_login_md5password", Utilities.md5(password))); nvps.add(new BasicNameValuePair("vb_login_md5password_utf", Utilities.md5(password))); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // execute the POST Utilities.debug("Executing POST"); HttpResponse response = httpclient.execute(httppost, localContext); Utilities.debug("POST response: " + response.getStatusLine()); assert response.getStatusLine().getStatusCode() == 200; //TODO: store the cookies //http://bit.ly/e7yY5i (CookieStore javadoc) Utilities.printCookieStore(cookieStore); // confirm we are logged in HttpGet httpget = new HttpGet(rootURL); response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); Document page = Jsoup.parse(EntityUtils.toString(entity)); EntityUtils.consume(entity); assert page != null; Utilities.debug("Checking that we are logged in.."); Element username_box = page.select("input[name=vb_login_username]").first(); assert username_box == null; Element password_box = page.select("input[name=vb_login_password]").first(); assert password_box == null; // parse the user's new securitytoken Element el_security_token = page.select("input[name=securitytoken]").first(); assert el_security_token != null; String security_token = el_security_token.attr("value"); assert security_token != null; String[] token_array = security_token.split("-"); assert token_array.length == 2; ret.vb_security_token = token_array[1]; assert ret.vb_security_token.length() == 40; Utilities.debug("securitytoken: " + ret.vb_security_token); Utilities.debug("Login seems ok"); ret.httpContext = localContext; } catch (IOException e) { System.out.println(e); } Utilities.debug("end login"); return ret; }
From source file:cn.com.zzwfang.http.HttpClient.java
public void setCookieStore(CookieStore cookieStore) { httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); }
From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java
private int read(HttpRequestBase request) { Log.v(TAG, "read"); CookieStore mCookieStore = new BasicCookieStore(); mCookieStore.addCookie(mAuthCookie); DefaultHttpClient httpClient = new DefaultHttpClient(); BasicHttpContext mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); try {/*from w w w . ja va 2 s . c om*/ final HttpParams getParams = new BasicHttpParams(); HttpClientParams.setRedirecting(getParams, false); request.setParams(getParams); request.setHeader("Accept", getMimeType()); 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:net.emphased.vkclient.VkApi.java
private CookieStore getCookieStore() { return (CookieStore) _httpContext.getAttribute(ClientContext.COOKIE_STORE); }
From source file:com.vanda.beivandalibnetwork.utils.HttpUtils.java
/** * ?Cookie?/* w w w .ja va 2 s . c o m*/ * * @param context * * @param name * Cookie?? * @return */ public static Cookie getCookie(final HttpContext context, String name) { HttpContext ctx = context == null ? CURRENT_CONTEXT : context; if (ctx == null) return null; CookieStore store = (CookieStore) ctx.getAttribute(ClientContext.COOKIE_STORE); if (store == null) return null; for (Cookie cookie : store.getCookies()) { if (cookie.getName().equals(name)) return cookie; } return null; }
From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java
@Override public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php"); List<ValidationResultEntry> validationResultEntries = new ArrayList<>(); try {//from w w w. j a va 2s .c om MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("uri", new StringBody("")); multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800")); multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html")); multipartEntity.addPart("validate_file", new StringBody("Check It")); multipartEntity.addPart("pastehtml", new StringBody("")); multipartEntity.addPart("radio_gid[]", new StringBody("8")); multipartEntity.addPart("checkbox_gid[]", new StringBody("8")); multipartEntity.addPart("rpt_format", new StringBody("1")); request.setEntity(multipartEntity); Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext); Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors"); String title = ""; StringBuilder descriptionSb = new StringBuilder(); boolean descriptionStarted = false; for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) { if ("h3".equals(e.getTagName())) { if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } title = e.getTextContent(); descriptionSb.setLength(0); descriptionStarted = false; } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) { if (descriptionStarted) { descriptionSb.append('\n'); } if (extractDescription(e, descriptionSb)) { descriptionStarted = true; } } } if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } } finally { request.releaseConnection(); } return new DefaultValidationResult("WAI Validation", fileToValidate.getName(), new DefaultValidationResultType("WAI"), validationResultEntries); }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
@Override public boolean deleteFromStore(APIIdentifier apiId, APIStore store) throws APIManagementException { boolean deleted = false; if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) { String msg = "External APIStore endpoint URL or credentials are not defined. " + "Cannot proceed with publishing API to the APIStore - " + store.getDisplayName(); throw new APIManagementException(msg); } else {// w w w . ja v a2 s. c om CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); boolean authenticated = authenticateAPIM(store, httpContext); if (authenticated) { deleted = deleteWSO2Store(apiId, store.getUsername(), store.getEndpoint(), httpContext, store.getDisplayName()); logoutFromExternalStore(store, httpContext); } return deleted; } }
From source file:com.ryan.ryanreader.cache.CacheDownload.java
private void downloadPost(final HttpClient httpClient) { final HttpPost httpPost = new HttpPost(initiator.url); try {/* w w w . j av a 2 s . c om*/ httpPost.setEntity(new UrlEncodedFormEntity(initiator.postFields, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { BugReportActivity.handleGlobalError(initiator.context, e); return; } final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, initiator.getCookies()); final HttpResponse response; final StatusLine status; try { response = httpClient.execute(httpPost, localContext); status = response.getStatusLine(); } catch (Throwable t) { t.printStackTrace(); notifyAllOnFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection"); return; } if (status.getStatusCode() != 200) { notifyAllOnFailure(RequestFailureType.REQUEST, null, status, String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase())); return; } final HttpEntity entity = response.getEntity(); if (entity == null) { notifyAllOnFailure(RequestFailureType.CONNECTION, null, status, "Did not receive a valid HTTP response"); return; } final InputStream is; try { is = entity.getContent(); } catch (Throwable t) { t.printStackTrace(); notifyAllOnFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream"); return; } if (initiator.isJson) { final BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024); final JsonValue value; try { value = new JsonValue(bis); value.buildInNewThread(); } catch (Throwable t) { t.printStackTrace(); notifyAllOnFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream"); return; } synchronized (this) { this.value = value; notifyAllOnJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session); } try { value.join(); } catch (Throwable t) { t.printStackTrace(); notifyAllOnFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream"); return; } success = true; } else { throw new RuntimeException("POST requests must be for JSON values"); } }