1

I have: a persistent text cookie file I want: to set that cookie for Selenium requests

Code:

// go on the domain so we can set the cookie
driver.get("https://www.thedomain.com/404");
try {Thread.sleep(2000);} catch (Exception e) {}

    try{
       File file = new File('CookieFile.txt');
       FileReader fileReader = new FileReader(file);
       BufferedReader Buffreader = new BufferedReader(fileReader);
       String strline;
       while((strline=Buffreader.readLine())!=null){
            StringTokenizer token = new StringTokenizer(strline,";");
            while(token.hasMoreTokens()){
                 String name = token.nextToken();
                 String value = token.nextToken();
                 String domain = token.nextToken();
                 String path = token.nextToken();
                 Date expiry = null;

                 String val;
                 if(!(val=token.nextToken()).equals("null"))
                  {
                     expiry = new Date(val);
                  }
        Boolean isSecure = new Boolean(token.nextToken()).
                            booleanValue();
        Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
        System.out.println(ck);
        driver.manage().addCookie(ck); // This will add the stored cookie to your current session
              }
          }
      }catch(Exception ex){
            ex.printStackTrace();
    }

Date String:

Mon Feb 15 15:38:00 CET 2021

Error by IDE:

java.lang.IllegalArgumentException

at java.util.Date.parse(Date.java:617)

at java.util.Date.(Date.java:274)

at MyClassName.testSaveCookie(MyClassName.java:196)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Writing/creating the cookie file works fine. It seems to have an issue with the Date object set. Any ideas?

Community
  • 1
  • 1
to_the_nth
  • 61
  • 11

1 Answers1

0

The java.util.Date(String) is deprecated for a reason and for a long time. You should check the following snippet:

    DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
    try {
      String s = df.format(d);
      System.out.println(s);
      d = df.parse(s);
    } catch (ParseException e) { 
      e.printStackTrace();
    }

That should fit your file. I would recommend to edit the cookie file and use a simple date and time format like

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

You would have to edit your file and use a format like 2019-02-16 17:30:44.

There is a concise description of date and time in How to convert a String to a Date using SimpleDateFormat?

I would recommend using the java.time package as described here Differences between Java 8 Date Time API (java.time) and Joda-Time.

Jens Dibbern
  • 1,434
  • 2
  • 13
  • 20