當前位置: 首頁>>代碼示例>>Java>>正文


Java Cookie類代碼示例

本文整理匯總了Java中org.openqa.selenium.Cookie的典型用法代碼示例。如果您正苦於以下問題:Java Cookie類的具體用法?Java Cookie怎麽用?Java Cookie使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Cookie類屬於org.openqa.selenium包,在下文中一共展示了Cookie類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getCookies

import org.openqa.selenium.Cookie; //導入依賴的package包/類
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;
}
 
開發者ID:google,項目名稱:devtools-driver,代碼行數:23,代碼來源:RemoteIOSWebDriver.java

示例2: close

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 關閉瀏覽器引擎
 */
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();
	}
}
 
開發者ID:LinuxSuRen,項目名稱:phoenix.webui.framework,代碼行數:29,代碼來源:SeleniumEngine.java

示例3: getAuthenticationCookie

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:NoraUi,項目名稱:NoraUi,代碼行數:30,代碼來源:Auth.java

示例4: getCookies

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:22,代碼來源:AbstractHtmlEngine.java

示例5: saveCookies

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:brunocvcunha,項目名稱:seleneasy,代碼行數:24,代碼來源:Seleneasy.java

示例6: saveCookies

import org.openqa.selenium.Cookie; //導入依賴的package包/類
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.");
}
 
開發者ID:Betalord,項目名稱:BHBot,代碼行數:25,代碼來源:MainThread.java

示例7: addCookie

import org.openqa.selenium.Cookie; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:18,代碼來源:CommonMethods.java

示例8: deleteCookie

import org.openqa.selenium.Cookie; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:19,代碼來源:CommonMethods.java

示例9: getHttpCookieString

import org.openqa.selenium.Cookie; //導入依賴的package包/類
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;
}
 
開發者ID:xbynet,項目名稱:crawler,代碼行數:17,代碼來源:WindowUtil.java

示例10: getSessionCookies

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:fjalvingh,項目名稱:domui,代碼行數:21,代碼來源:WebDriverConnector.java

示例11: writeFile

import org.openqa.selenium.Cookie; //導入依賴的package包/類
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();
    }
}
 
開發者ID:Airpy,項目名稱:KeywordDrivenAutoTest,代碼行數:22,代碼來源:FileUtils.java

示例12: getCookieValueByNameFromFile

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 從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!");
    }
}
 
開發者ID:Airpy,項目名稱:KeywordDrivenAutoTest,代碼行數:22,代碼來源:WebCookies.java

示例13: getCookieByNameFromFile

import org.openqa.selenium.Cookie; //導入依賴的package包/類
/**
 * 從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!");
    }
}
 
開發者ID:Airpy,項目名稱:KeywordDrivenAutoTest,代碼行數:22,代碼來源:WebCookies.java

示例14: compare

import org.openqa.selenium.Cookie; //導入依賴的package包/類
@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;
}
 
開發者ID:Cognifide,項目名稱:aet,代碼行數:27,代碼來源:CookieComparator.java

示例15: enableSession

import org.openqa.selenium.Cookie; //導入依賴的package包/類
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);
        });
        
    }
}
 
開發者ID:watchrabbit,項目名稱:rabbit-crawler,代碼行數:22,代碼來源:CrawlExecutorServiceImpl.java


注:本文中的org.openqa.selenium.Cookie類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。