Java 类org.openqa.selenium.Cookie 实例源码

项目:phoenix.webui.framework    文件:SeleniumEngine.java   
/**
 * 关闭浏览器引擎
 */
public void close()
{
    if(driver != null)
    {
        Options manage = driver.manage();
        boolean cookieSave = Boolean.parseBoolean(enginePro.getProperty("cookie.save", "false"));
        File root = PathUtil.getRootDir();
        File cookieFile = new File(root, enginePro.getProperty("cookie.save.path", "phoenix.autotest.cookie"));

        if(cookieSave)
        {
            Set<Cookie> cookies = manage.getCookies();
            try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(cookieFile)))
            {
                output.writeObject(cookies);
            }
            catch (IOException e)
            {
                logger.error("", e);
            }
        }

        driver.quit();
    }
}
项目:NoraUi    文件:Auth.java   
/**
 * Returns a Cookie object by retrieving data from -Dcookie maven parameter.
 *
 * @param domainUrl
 *            is url of guardian domain
 * @return a Cookie with a name, value, domain and path.
 * @throws TechnicalException
 *             with a message (no screenshot, no exception)
 */
public static Cookie getAuthenticationCookie(String domainUrl) throws TechnicalException {
    if (getInstance().authCookie == null) {
        String cookieStr = System.getProperty(SESSION_COOKIE);
        try {
            if (cookieStr != null && !"".equals(cookieStr)) {
                int indexValue = cookieStr.indexOf('=');
                int indexPath = cookieStr.indexOf(",path=");
                String cookieName = cookieStr.substring(0, indexValue);
                String cookieValue = cookieStr.substring(indexValue + 1, indexPath);
                String cookieDomain = new URI(domainUrl).getHost().replaceAll("self.", "");
                String cookiePath = cookieStr.substring(indexPath + 6);
                getInstance().authCookie = new Cookie.Builder(cookieName, cookieValue).domain(cookieDomain).path(cookiePath).build();
                logger.debug("New cookie created: {}={} on domain {}{}", cookieName, cookieValue, cookieDomain, cookiePath);
            }
        } catch (URISyntaxException e) {
            throw new TechnicalException(Messages.getMessage(WRONG_URI_SYNTAX), e);
        }
    }
    return getInstance().authCookie;
}
项目:ats-framework    文件:AbstractHtmlEngine.java   
/**
 * Get all the cookies for the current domain. This is the equivalent of calling "document.cookie" and parsing the result
 *
 * @return {@link com.axway.ats.uiengine.elements.html.Cookie Cookie}s array
 */
@PublicAtsApi
public com.axway.ats.uiengine.elements.html.Cookie[] getCookies() {

    Set<Cookie> cookies = webDriver.manage().getCookies();
    com.axway.ats.uiengine.elements.html.Cookie[] cookiesArr = new com.axway.ats.uiengine.elements.html.Cookie[cookies.size()];
    int i = 0;
    for (Cookie c : cookies) {
        cookiesArr[i++] = new com.axway.ats.uiengine.elements.html.Cookie(c.getName(),
                                                                          c.getValue(),
                                                                          c.getDomain(),
                                                                          c.getPath(),
                                                                          c.getExpiry(),
                                                                          c.isSecure());
    }
    return cookiesArr;
}
项目:devtools-driver    文件:RemoteIOSWebDriver.java   
public List<Cookie> getCookies() {
  List<Cookie> res = new ArrayList<>();
  JsonObject o = inspector.sendCommand(Page.getCookies());
  JsonArray cookies = o.getJsonArray("cookies");
  if (cookies != null) {
    for (int i = 0; i < cookies.size(); i++) {
      JsonObject cookie = cookies.getJsonObject(i);
      String name = cookie.getString("name");
      String value = cookie.getString("value");
      String domain = cookie.getString("domain");
      String path = cookie.getString("path");
      Date expiry = new Date(cookie.getJsonNumber("expires").longValue());
      boolean isSecure = cookie.getBoolean("secure");
      Cookie c = new Cookie(name, value, domain, path, expiry, isSecure);
      res.add(c);
    }
    return res;
  } else {
    // TODO
  }
  return null;
}
项目:seleneasy    文件:Seleneasy.java   
/**
 * Save the cookies to a file
 * @param file File to save
 * @param append Append to the previous cookies in the file
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws ClassNotFoundException 
 */
public void saveCookies(File file, boolean append) throws FileNotFoundException, IOException, ClassNotFoundException {
    log.info("Saving cookies: " + file.getAbsolutePath());

    Set<Cookie> cookiesToSave;
    if (append) {
        cookiesToSave = getCookies(file);
        cookiesToSave.addAll(driver.manage().getCookies());
    } else {
        cookiesToSave = driver.manage().getCookies();
    }

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
    oos.writeObject(cookiesToSave);
    oos.close();
}
项目:BHBot    文件:MainThread.java   
public static void saveCookies() {
    // create file named Cookies to store Login Information     
    File file = new File("Cookies.data");                           
    try     
    {       
        // Delete old file if exists
        file.delete();
        file.createNewFile();           
        FileWriter fileWrite = new FileWriter(file);                            
        BufferedWriter Bwrite = new BufferedWriter(fileWrite);                          
        // loop for getting the cookie information      
        for(Cookie ck : driver.manage().getCookies()) {
            Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+(ck.getExpiry()==null ? 0 : ck.getExpiry().getTime())+";"+ck.isSecure()));                                                                                                 
            Bwrite.newLine();           
        }
        Bwrite.flush();         
        Bwrite.close();         
        fileWrite.close();          
    } catch(Exception ex) {     
        ex.printStackTrace();           
    }

    BHBot.log("Cookies saved to disk.");
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CommonMethods.java   
@Action(object = ObjectType.BROWSER, desc = "Add the cookie of name with value [<Data>].", input = InputType.YES)
public void addCookie() {

    try {
        String strCookieName = Data.split(":", 2)[0];
        String strCookieValue = Data.split(":", 2)[1];
        Cookie oCookie = new Cookie.Builder(strCookieName, strCookieValue)
                .build();
        Driver.manage().addCookie(oCookie);
        Report.updateTestLog(Action, "Cookie Name- '" + strCookieName
                + "' with value '" + strCookieValue + "' is added",
                Status.DONE);
    } catch (Exception e) {
        Report.updateTestLog(Action, e.getMessage(), Status.FAIL);
        Logger.getLogger(CommonMethods.class.getName()).log(Level.SEVERE, null, e);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CommonMethods.java   
@Action(object = ObjectType.BROWSER, desc = "delete the cookie having name [<Data>].", input = InputType.YES)
public void deleteCookie() {
    try {
        String strCookieName = Data;
        Cookie oCookie = Driver.manage().getCookieNamed(strCookieName);
        if (oCookie != null) {
            Driver.manage().deleteCookie(oCookie);
            Report.updateTestLog(Action, "Cookie Name- '"
                    + strCookieName + "' is deleted", Status.DONE);
        } else {
            Report.updateTestLog(Action, "Cookie doesn't exist",
                    Status.FAIL);
        }
    } catch (Exception e) {
        Report.updateTestLog(Action, e.getMessage(), Status.FAIL);
        Logger.getLogger(CommonMethods.class.getName()).log(Level.SEVERE, null, e);
    }
}
项目:crawler    文件:WindowUtil.java   
public static String getHttpCookieString(Set<Cookie> cookies){
    if(cookies==null){
        return "";
    }
    String httpCookie="";
    int index=0;
    for(Cookie c:cookies){
        index++;
        if(index==cookies.size()){
            httpCookie+=c.getName()+"="+c.getValue();
        }else{
            httpCookie+=c.getName()+"="+c.getValue()+"; ";
        }
    }
    return httpCookie;
}
项目:domui    文件:WebDriverConnector.java   
/**
 * This obtains a list of session cookies that should be used to talk with the
 * remote server using the same session.
 * @return
 */
@Nonnull
private List<Cookie> getSessionCookies() {
    List<Cookie> res = new ArrayList<Cookie>();
    Cookie cookie = driver().manage().getCookieNamed("JSESSIONID"); // Tomcat specific.
    if(null != cookie)
        res.add(cookie);

    //-- FIXME Add other server's state cookie names here.


    //--
    if(res.size() == 0)
        throw new IllegalStateException("Cannot obtain session cookies");
    return res;
}
项目:KeywordDrivenAutoTest    文件:FileUtils.java   
public static void writeFile(String fileName, Set<Cookie> cookies) {
    try {
        File file = new File(fileName);
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        for (Cookie cookie : cookies) {
            String strCookie = cookie.getName() + ";" + cookie.getValue() + ";" + cookie.getDomain() + ";"
                    + cookie.getPath() + ";" + cookie.getExpiry() + ";" + cookie.isSecure() + ";"
                    + cookie.isHttpOnly();
            bufferedWriter.write(strCookie);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
        bufferedWriter.close();
        fileWriter.close();
        LogUtils.info("写文件[" + fileName + "]操作成功");
    } catch (Exception e) {
        LogUtils.error("写文件[" + fileName + "]操作失败: " + e.getMessage());
        e.printStackTrace();
    }
}
项目:KeywordDrivenAutoTest    文件:WebCookies.java   
/**
 * 从Cookie文件中根据Cookie名称获取Cookie值
 *
 * @param cookieName Cookie名称
 * @return Cookie值
 */
public static String getCookieValueByNameFromFile(String cookieName) {
    Set<Cookie> cookies = FileUtils.getAllCookiesFromFile(cookiePath);
    String cookieValue = null;
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase(cookieName)) {
            cookieValue = cookie.getValue();
            break;
        }
    }
    if (null != cookieValue) {
        return cookieValue;
    } else {
        throw new RuntimeException("cookie文件中不存在cookie名为[" + cookieName + "]的cookie!");
    }
}
项目:KeywordDrivenAutoTest    文件:WebCookies.java   
/**
 * 从Cookie文件中根据Cookie名称获取Cookie
 *
 * @param cookieName Cookie名称
 * @return Cookie对象
 */
public static Cookie getCookieByNameFromFile(String cookieName) {
    Set<Cookie> cookies = FileUtils.getAllCookiesFromFile(cookiePath);
    Cookie tempCookie = null;
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase(cookieName)) {
            tempCookie = cookie;
            break;
        }
    }
    if (null != tempCookie) {
        return tempCookie;
    } else {
        throw new RuntimeException("cookie文件中不存在cookie名为[" + cookieName + "]的cookie!");
    }
}
项目:aet    文件:CookieComparator.java   
@Override
@SuppressWarnings("unchecked")
public ComparatorStepResult compare() throws ProcessingException {
  ComparatorStepResult result;
  try {
    final Set<Cookie> cookies = artifactsDAO
        .getJsonFormatArtifact(properties, properties.getCollectedId(),
            COOKIES_SET_TYPE);
    switch (compareAction) {
      case TEST:
        result = testCookie(cookies);
        break;
      case COMPARE:
        result = compareCookies(cookies);
        break;
      case LIST:
      default:
        result = listCookies(cookies);
        break;
    }
    result.addData("compareAction", compareAction.name());
  } catch (IOException e) {
    throw new ProcessingException("Error while obtaining cookies from " + properties, e);
  }
  return result;
}
项目:rabbit-crawler    文件:CrawlExecutorServiceImpl.java   
private void enableSession(RemoteWebDriver driver, CrawlForm form, Collection<Cookie> session) {
    driver.get(form.getUrl());
    loaderService.waitFor(driver);
    if (!session.isEmpty()) {
        driver.manage().deleteAllCookies();
        session.forEach(driver.manage()::addCookie);

        driver.get(form.getUrl());
        loaderService.waitFor(driver);
    }
    if (StringUtils.isNotEmpty(form.getKeyword())) {
        Optional<SearchForm> searchFormOptional = findSearchInput(driver);
        searchFormOptional.ifPresent(searchForm -> {
            searchForm.input.sendKeys(form.getKeyword());
            loaderService.waitFor(driver);
            searchForm.submit.click();
            loaderService.waitFor(driver);
        });

    }
}
项目:SeInterpreter-Java    文件:AddCookie.java   
@Override
public boolean run(TestRun ctx) {
    Cookie.Builder cb = new Cookie.Builder(ctx.string("name"), ctx.string("value"));
    for (String opt : ctx.string("options").split(",")) {
        String[] kv = opt.split("=", 2);
        if (kv.length == 1) { continue; }
        if (kv[0].trim().equals("path")) {
            cb.path(kv[1].trim());
        }
        if (kv[0].trim().equals("max_age")) {
            cb.expiresOn(new Date(new Date().getTime() + Long.parseLong(kv[1].trim()) * 1000l));
        }
        ctx.driver().manage().addCookie(cb.build());
    }
    ctx.driver().navigate().refresh();
    return true;
}
项目:rise    文件:ProgrammaticAuthenticationControllerTest.java   
@Test
public void testAuthenticationRequired_tokenTheft() throws Exception {
    deleteAllCookies();
    loadAuthRequired();
    pageObject(LoginPO.class).defaultLogin();

    // modify stored token
    Cookie cookie = driver.manage().getCookieNamed(config.rememberMeCookieName);
    String value = cookie.getValue();
    if (value.startsWith("\""))
        value = value.substring(1);
    if (value.endsWith("\""))
        value = value.substring(0, value.length() - 1);
    RememberMeToken token = RememberMeAuthenticationProvider.parseToken(value);
    dao.updateToken(token.withToken(new byte[] { 1 }));

    // try remember me
    clearSession();
    loadAuthRequired();
    assertPage(LoginController.class, x -> x.tokenTheftDetected(null));
}
项目:grid-refactor-remote-server    文件:AddCookie.java   
protected Cookie createCookie() {
  if (rawCookie == null) {
    return null;
  }

  String name = (String) rawCookie.get("name");
  String value = (String) rawCookie.get("value");
  String path = (String) rawCookie.get("path");
  String domain = (String) rawCookie.get("domain");
  Boolean secure = (Boolean) rawCookie.get("secure");
  if (secure == null) {
      secure = false;
  }

  Number expiryNum = (Number) rawCookie.get("expiry");
  Date expiry = expiryNum == null ? null : new Date(
      TimeUnit.SECONDS.toMillis(expiryNum.longValue()));

  return new Cookie.Builder(name, value)
      .path(path)
      .domain(domain)
      .isSecure(secure)
      .expiresOn(expiry)
      .build();
}
项目:detective    文件:GebDetectivePage.java   
/**
 * Share the cookies with HttpClientTask
 */
public void shareCookies(){
  Object store = getCookieStore();
  if (store == null){
    store = new BasicCookieStore();
    this.getParametersInner().put(HttpClientTask.PARAM_HTTP_COOKIES, store);
  }

  CookieStore cookieStore = (CookieStore)store; 
  for (Cookie cookie : this.getDriver().manage().getCookies()){
    BasicClientCookie newCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
    newCookie.setDomain(cookie.getDomain());
    newCookie.setPath(cookie.getPath());
    newCookie.setExpiryDate(cookie.getExpiry());
    newCookie.setSecure(cookie.isSecure());
    cookieStore.addCookie(newCookie);
  }
}
项目:DAAExample    文件:PeopleWebTest.java   
@Before
public void setUp() throws Exception {
    final String baseUrl = "http://localhost:9080/DAAExample/";

    driver = new FirefoxDriver();
    driver.get(baseUrl);

    // Driver will wait DEFAULT_WAIT_TIME if it doesn't find and element.
    driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_TIME, TimeUnit.SECONDS);

    // Login as "admin:adminpass"
    driver.manage().addCookie(new Cookie("token", "YWRtaW46YWRtaW5wYXNz"));

    mainPage = new MainPage(driver, baseUrl);
    mainPage.navigateTo();
}
项目:hsac-fitnesse-fixtures    文件:CookieConverter.java   
/**
 * Converts Selenium cookie to Apache http client.
 * @param browserCookie selenium cookie.
 * @return http client format.
 */
protected ClientCookie convertCookie(Cookie browserCookie) {
    BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue());
    String domain = browserCookie.getDomain();
    if (domain != null && domain.startsWith(".")) {
        // http client does not like domains starting with '.', it always removes it when it receives them
        domain = domain.substring(1);
    }
    cookie.setDomain(domain);
    cookie.setPath(browserCookie.getPath());
    cookie.setExpiryDate(browserCookie.getExpiry());
    cookie.setSecure(browserCookie.isSecure());
    if (browserCookie.isHttpOnly()) {
        cookie.setAttribute("httponly", "");
    }
    return cookie;
}
项目:automation-test-engine    文件:EadSaveLoadAllCookiesTest.java   
/**
 * Ead load cookies test.
 * 
 * @throws RuntimeDataException
 * @throws PageValidationException
 * @throws StepExecutionException
 * @throws BrowserUnexpectedException 
 * @throws NoSuchElementException 
 */
//@Test(priority = 2)
public void eadLoadCookiesTest() throws PageValidationException,
        RuntimeDataException, StepExecutionException, NoSuchElementException, BrowserUnexpectedException {

    WebDriver webDriver = getMyDriver().getWebDriverInstance();
    webDriver.manage().deleteAllCookies();
    Assert.assertTrue(webDriver.manage().getCookies().isEmpty());

    MyWebElement<?> testEad = (MyWebElement<?>) getApplicationContext()
            .getBean("eadLoadCookies");
    testEad.doAction();

    Set<Cookie> loadedCookies = webDriver.manage().getCookies();
    Assert.assertTrue(!originalCookies.isEmpty());
    Assert.assertEquals(originalCookies, loadedCookies);

}
项目:oxAuth    文件:BaseTest.java   
private AuthorizationResponse buildAuthorizationResponse(AuthorizationRequest authorizationRequest,
        boolean useNewDriver, WebDriver currentDriver, AuthorizeClient authorizeClient,
        String authorizationResponseStr) {
    Cookie sessionStateCookie = currentDriver.manage().getCookieNamed("session_state");
       String sessionState = null;
       if (sessionStateCookie != null) {
           sessionState = sessionStateCookie.getValue();
       }
       System.out.println("authenticateResourceOwnerAndGrantAccess: sessionState:" + sessionState);

       AuthorizationResponse authorizationResponse = new AuthorizationResponse(authorizationResponseStr);
       if (authorizationRequest.getRedirectUri() != null && authorizationRequest.getRedirectUri().equals(authorizationResponseStr)) {
           authorizationResponse.setResponseMode(ResponseMode.FORM_POST);
       }
       authorizeClient.setResponse(authorizationResponse);
       showClientUserAgent(authorizeClient);

       return authorizationResponse;
}
项目:seleniumcapsules    文件:CookieTest.java   
@Test
public void cookies() {
    WebDriver driver = new ChromeDriver();
    driver.get("http://ticketfly.com");

    Options manage = driver.manage();
    manage.getCookies().stream().forEach(System.out::println);
    manage.deleteAllCookies();
    System.out.println("After manage.deleteAllCookies();");
    manage.getCookies().stream().forEach(System.out::println);
    System.out.println("After adding two cookies");

    manage.addCookie(new Cookie("Test", "just for test"));
    manage.addCookie(new Cookie("Test2", "just for test too"));
    manage.getCookies().stream().forEach(System.out::println);

    Cookie test = manage.getCookieNamed("Test");
    System.out.println("Test Cookie is:" + test);
    manage.deleteCookie(test);

    manage.deleteCookieNamed("Test2");
    System.out.println("After deleting two cookies");
    manage.getCookies().stream().forEach(System.out::println);
    System.out.println("Done");
}
项目:gga-selenium-framework    文件:FileUtil.java   
/**
 * Get Cookie from WebDriver browser session.
 *
 * @return cookieStore from WebDriver browser session.
 */
private static CookieStore seleniumCookiesToCookieStore() {

    Set<Cookie> seleniumCookies = WebDriverWrapper.getDriver().manage().getCookies();
    CookieStore cookieStore = new BasicCookieStore();

    for (Cookie seleniumCookie : seleniumCookies) {
        BasicClientCookie basicClientCookie =
                new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
        basicClientCookie.setDomain(seleniumCookie.getDomain());
        basicClientCookie.setExpiryDate(seleniumCookie.getExpiry());
        basicClientCookie.setPath(seleniumCookie.getPath());
        cookieStore.addCookie(basicClientCookie);
    }

    return cookieStore;
}
项目:burp-csj    文件:SetupCrawljax.java   
private void setCookies(WebDriver drivertest, String browserName) {
    List<ICookie> cookies = callbacks.getCookieJarContents();
    try {
        drivertest.get(url);
        if (browserName.equalsIgnoreCase("IEBrowser")) {
            drivertest.navigate().to("javascript:document.getElementById('overridelink').click()");
        }
        drivertest.manage().deleteAllCookies();
        URL Url = new URL(url);
        for (ICookie o : cookies) {
            String fullhost = Url.getHost();
            if (o.getDomain().equalsIgnoreCase(fullhost)) {
                drivertest.manage().addCookie(new Cookie(o.getName(), o.getValue(), o.getDomain(), "/", null));
            }
        }
    } catch (MalformedURLException e) {
        System.out.println("WebDriver setCookies Error: " + e.getMessage());
    }
}
项目:selenium-on-steroids    文件:WebDriverHelper.java   
/**
 * Verifies that the given cookie name has the given cookie value. This
 * method is also add logging info.
 * 
 * @param cookieName
 *            the cookie name
 * @param cookieValue
 *            the cookie value
 * @return true if the given cookie name exists and its value matches the
 *         given cookie value; false otherwise
 */
public boolean verifyCookie(final String cookieName,
        final String cookieValue) {
    Set<Cookie> cookies = driver.manage().getCookies();

    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(cookieName)
                && cookie.getValue().equals(cookieValue)) {
            LOG.info("Cookie: " + cookieName + " was found with value: "
                    + cookie.getValue());
            return true;
        }
    }

    LOG.info("Cookie: " + cookieName + " with value: " + cookieValue
            + " NOT found!");
    return false;
}
项目:selenium-on-steroids    文件:WebDriverHelper.java   
/**
 * Verifies that the given cookie name has the given cookie value. This
 * method is also add logging info. Please not that the method will do a
 * JUNIT Assert causing the test to fail.
 * 
 * @param cookieName
 *            the cookie name
 * @param cookieValue
 *            the cookie value
 */
public void assertCookie(final String cookieName, final String cookieValue) {
    Set<Cookie> cookies = driver.manage().getCookies();

    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(cookieName)
                && cookie.getValue().equals(cookieValue)) {
            LOG.info("Cookie: " + cookieName + " was found with value: "
                    + cookie.getValue());
            return;
        }
    }

    Assert.fail("Cookie: " + cookieName + " with value: " + cookieValue
            + " NOT found!");

}
项目:jspider    文件:WebDriverDownloader.java   
private Header[] getHeaderFromCookieSet(Set<Cookie> cookieSet) {
    if (cookieSet != null && cookieSet.size() > 0) {
        List<Header> headers = new ArrayList<Header>(cookieSet.size());
        for (Cookie cookie : cookieSet) {
            headers.add(new BasicHeader("Set-Cookie", cookie.toString()));
        }
        return headers.toArray(new Header[headers.size()]);
    }
    return null;
}
项目:teasy    文件:CookiesService.java   
private List<Cookie> addCookie(final HttpResponse httpResponse) {
    String cookieValue = "";
    List<Cookie> cookieList = new ArrayList<Cookie>();
    for (Header header : httpResponse.getHeaders("Set-Cookie")) {
        List<HttpCookie> httpCookies = HttpCookie.parse(header.getValue());
        for (HttpCookie httpCookie : httpCookies) {
            if (!cookieValue.isEmpty()) {
                cookieValue += "; ";
            }
            cookieList.add(new Cookie(httpCookie.getName(), httpCookie.getValue(), httpCookie.getDomain(), httpCookie.getPath(), null, httpCookie.getSecure(), httpCookie.isHttpOnly()));
        }
    }
    return cookieList;
}
项目:teasy    文件:CookiesService.java   
public void addCookiesToDriver(HttpResponse httpResponse) {
    for (Cookie cookie : addCookie(httpResponse)) {
        if (SeleniumHolder.getDriverName().equals("chrome")) {
            //to avoid WebDriverException: Failed to set the 'cookie' property on 'Document': Cookies are disabled inside 'data:' URLs.
            getWebDriver().get("chrome://settings/cookies");
        }
        getWebDriver().manage().addCookie(cookie);
    }
}
项目:FashionSpider    文件:WeiboLoginAndGetCookie.java   
public static void main(String[] args) throws Exception{
    //配置ChromeDiver
    System.getProperties().setProperty("webdriver.chrome.driver", "chromedriver.exe");
    //开启新WebDriver进程
    WebDriver webDriver = new ChromeDriver();
    //全局隐式等待
    webDriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    //设定网址
    webDriver.get("https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F");
    //显示等待控制对象
    WebDriverWait webDriverWait=new WebDriverWait(webDriver,10);
    //等待输入框可用后输入账号密码
    webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginName"))).sendKeys(args[0]);
    webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginPassword"))).sendKeys(args[1]);
    //点击登录
    webDriver.findElement(By.id("loginAction")).click();
    //等待2秒用于页面加载,保证Cookie响应全部获取。
    sleep(2000);
    //获取Cookie并打印
    Set<Cookie> cookies=webDriver.manage().getCookies();
    Iterator iterator=cookies.iterator();
    while (iterator.hasNext()){
        System.out.println(iterator.next().toString());
    }
    //关闭WebDriver,否则并不自动关闭
    webDriver.close();
}
项目:phoenix.webui.framework    文件:KaptchaInvoker.java   
/**
 * 获取验证码
 * @param engine 引擎
 * @param param 例如:data,http://localhost:8080/G2/captcha!getLastCode.do
 * @return 验证码
 */
public static String execute(SeleniumEngine engine, String param)
{
    WebDriver driver = engine.getDriver();
    Options manage = driver.manage();

    String[] paramArray = param.split(",", 2);

    if(paramArray.length != 2)
    {
        throw new RuntimeException("Param format is error, should be 'data,url'");
    }

    String key = paramArray[0];
    String url = paramArray[1];

    Set<Cookie> cookies = manage.getCookies();
    List<AtCookie> atCookieList = new ArrayList<AtCookie>();
    for(Cookie cookie : cookies)
    {
        String name = cookie.getName();
        String value = cookie.getValue();

        AtCookie atCookie = new AtCookie();
        atCookie.setName(name);
        atCookie.setValue(value);
        atCookie.setPath(cookie.getPath());
        atCookie.setDomain(cookie.getDomain());

        atCookieList.add(atCookie);
    }

    String code = HttpApiUtil.getJsonValue(url, atCookieList, key);

    return code;
}
项目:Gospy    文件:PhantomJSFetcher.java   
private PhantomJSFetcher(String phantomJsBinaryPath, int timeout, boolean loadImages, String userAgent, Collection<Cookie> cookies) {
    System.setProperty("phantomjs.binary.path", phantomJsBinaryPath);
    DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    capabilities.setCapability("phantomjs.page.settings.resourceTimeout", timeout);
    capabilities.setCapability("phantomjs.page.settings.loadImages", loadImages);
    capabilities.setCapability("phantomjs.page.settings.userAgent", userAgent);
    this.webDriver = new PhantomJSDriver(capabilities);
    this.userAgent = userAgent;
    this.cookies = cookies;
}
项目:ats-framework    文件:AbstractHtmlEngine.java   
/**
 *
 * @param cookieName the name of the cookie. May not be null or an empty string.
 * @param cookieValue the cookie value. May not be null.
 */
@PublicAtsApi
public void setCookie(
                       String cookieName,
                       String cookieValue ) {

    Cookie cookie = new Cookie(cookieName, cookieValue);
    webDriver.manage().addCookie(cookie);
}
项目:ats-framework    文件:AbstractHtmlEngine.java   
/**
 *
 * @param name the name of the cookie. May not be null or an empty string.
 * @param value the cookie value. May not be null.
 * @param domain the domain the cookie is visible to.
 * @param path the path the cookie is visible to. If left blank or set to null, will be set to
 *        "/".
 * @param expiry the cookie's expiration date; may be null.
 * @param isSecure whether this cookie requires a secure connection.
 */
@PublicAtsApi
public void setCookie(
                       String name,
                       String value,
                       String domain,
                       String path,
                       Date expiry,
                       boolean isSecure ) {

    Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);
    webDriver.manage().addCookie(cookie);
}
项目:devtools-driver    文件:DeleteAllCookiesHandler.java   
@Override
public Response handle() throws Exception {
  String url = getWebDriver().getCurrentUrl();
  List<Cookie> cookies = getWebDriver().getCookies();
  for (Cookie c : cookies) {
    getWebDriver().deleteCookie(c.getName(), url);
  }

  Response res = new Response();
  res.setSessionId(getSession().getSessionId());
  res.setStatus(0);
  res.setValue(new JSONObject());
  return res;
}
项目:devtools-driver    文件:GetCookiesHandler.java   
@Override
public Response handle() throws Exception {

  List<Cookie> cookies = getWebDriver().getCookies();
  Response res = new Response();
  res.setSessionId(getSession().getSessionId());
  res.setStatus(0);
  res.setValue(cookies);
  return res;
}
项目:mot-automated-testsuite    文件:WebDriverWrapper.java   
/**
 * Deletes the specified cookie.
 * @param name      The cookie name (can be a partial match)
 */
public void deleteCookie(String name) {
    Cookie cookie = webDriver.manage().getCookies().stream()
            .filter((Cookie c) -> c.getName().contains(name))
            .findFirst().orElseThrow(() -> {
                return new IllegalStateException("Cookie with name containing " + name + " not found");
            });

    webDriver.manage().deleteCookie(cookie);
}
项目:seleneasy    文件:Seleneasy.java   
private Set<Cookie> getCookies(File file) throws IOException, FileNotFoundException, ClassNotFoundException {
    if (!file.exists()) {
        return new LinkedHashSet<>();
    }

    ObjectInputStream ios = new ObjectInputStream(new FileInputStream(file));
    Set<Cookie> cookies = (Set<Cookie>) ios.readObject();
    ios.close();
    return new LinkedHashSet<>(cookies);
}