I have cookies txt file with generated data from Chrome extension is look like this:
# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This is a generated file! Do not edit.
.site.net TRUE / FALSE 1701453620 _ga GA1.2.10834324067.1638446981
.site.net TRUE / FALSE 1638123020 _gid GA1.2.25433025264.1638446981
.site.net TRUE / FALSE 1646432624 _fbp fb.1.1643546988197.973328968
I need to load it to hashmap and to use it in Jsoup connection
HashMap<String,String> coockies = load.file
Document doc = Jsoup.connect(mainUrl).cookies(cookies).get();
It is possible to load the txt file and to convert it to hashMap
I would first pre-process the text file to get a key-value list. Something like this:
grep "^[^#]" cookies.txt | awk '{print $6 " " $7}'
_ga GA1.2.10834324067.1638446981
_gid GA1.2.25433025264.1638446981
_fbp fb.1.1643546988197.973328968
The code above strips off lines beginning with a #
and empty lines. Next, the result is filtered to only select the 6th (cookie name) and 7th (cookie value) column.
If you save the output of the above bash command into filtered.txt
, you can parse cookie information in Java like so:
Map<String, String> cookies = new HashMap<>();
try (Stream<String> stream = Files.lines(Paths.get("filtered.txt"))) {
stream.forEach(line -> {
String[] columns = line.split(" ");
cookies.put(columns[0], columns[1]);
});
}
We are simply grabbing the key and value from every row to fill our cookies
map; I suppose the code could be shorter, however, at the expense of readability.