[JAVA] Insert the selenium cookie into the okHttp3 client

Take the cookie from the selenium (same as selenide) webdriver and plug it into the okhttp client

Since the type is different, I had to hand it over. I thought I could do better, but I gave up. Below is an example of downloading a url

    private void downloadFileSync(final String downloadUrl, String orgFilename) throws Exception {
        List<Cookie> cookies = new ArrayList();
        String domain = "example.com";// .Domains starting with k are an exception, so k.getDomain()After taking.Or specify directly
        val cc = new Cookie.Builder();
        for (org.openqa.selenium.Cookie k : getWebDriver().manage().getCookies()) {
            cc.domain(domain).name(k.getName()).path(k.getPath()).value(k.getValue());
            if (k.isSecure()) { cc.secure(); }
            if (k.isHttpOnly()) { cc.httpOnly(); }
            if (k.getExpiry() != null) { cc.expiresAt(k.getExpiry().getTime()); }
            cookies.add(cc.build());
        }
        CookieManager cookieManager = new CookieManager(null, ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
        cookieJar.saveFromResponse(HttpUrl.parse(downloadUrl), cookies);
        OkHttpClient client = new OkHttpClient().newBuilder().cookieJar(cookieJar).build();

        String filename = orgFilename + ".jpg ";
        log.info("download filename : {}", filename);
        Request request = new Request.Builder().url(downloadUrl).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Failed to download file: " + response);
        }
        FileOutputStream fos = new FileOutputStream("/tmp/" + filename);
        fos.write(response.body().bytes());
        fos.close();
    }

In ChromeDriver, I couldn't find a way to get the image file etc. by get (url), so I passed the url to okhttp as described above to make it consistent with the cookie.

Or

        String[] cookieKeys = { "hoge", "hogehoge", "hogehogehoge" };
        StringBuilder cookie = new StringBuilder();
        for (String key : cookieKeys) {
            val oneCookie = getWebDriver().manage().getCookieNamed(key);
            cookie.append(String.format("%s=%s;", key, oneCookie.getValue()));
        }

        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder().url(downloadUrl).header("Cookie", cookie.toString()).build();

        Response response = client.newCall(request).execute();

It was good just to put it in the header like this. I wish getWebDriver (). Manage (). GetCookie () could be completely taken as a String. Can you do it?

over.

Recommended Posts

Insert the selenium cookie into the okHttp3 client
SetCookie from the client side with OkHttp3