selenium.Cookie 转 okhttp3.Cookie

package org.rx.util;

import lombok.SneakyThrows;
import okhttp3.HttpUrl;
import org.openqa.selenium.Cookie;
import org.rx.core.NQuery;
import org.rx.socks.http.HttpClient;

import java.util.Date;
import java.util.Set;

import static org.rx.core.Contract.require;

public class CookieExtend {
    public static void saveFromResponse(String url, Set cookieSet) {
        require(url, cookieSet);

        HttpClient.CookieContainer.getCookieJar().saveFromResponse(HttpUrl.get(url), NQuery.of(cookieSet).select(p -> {
            String domain = p.getDomain();
            if (domain.startsWith(".")) {
                domain = domain.substring(1);
            }
            okhttp3.Cookie.Builder builder = new okhttp3.Cookie.Builder().name(p.getName()).value(p.getValue())
                    .domain(domain)
                    .path(p.getPath());
            if (p.getExpiry() != null) {
                builder = builder.expiresAt(p.getExpiry().getTime());
            }
            if (p.isSecure()) {
                builder = builder.secure();
            }
            if (p.isHttpOnly()) {
                builder = builder.httpOnly();
            }
            return fill(builder.build(), p.getDomain());
        }).toList());
    }

    @SneakyThrows
    private static okhttp3.Cookie fill(okhttp3.Cookie cookie, String domain) {
//        Field field = Cookie.class.getDeclaredField("domain");
//        field.setAccessible(true);
//        field.set(cookie, domain);
        return cookie;
    }

    public static Set loadForRequest(String url) {
        require(url);

        return NQuery.of(HttpClient.CookieContainer.getCookieJar().loadForRequest(HttpUrl.get(url)))
                .select(p -> new org.openqa.selenium.Cookie(p.name(), p.value(), p.domain(), p.path(), new Date(p.expiresAt()), p.secure(), p.httpOnly())).toSet();
    }
}

 

HttpServletRequest request = getCurrentRequest();
if (request == null) {
return supplier.invoke(key);
}
v = request.getAttribute(k);
if (v == null) {
request.setAttribute(k, v = supplier.invoke(k));
}

你可能感兴趣的:(selenium.Cookie 转 okhttp3.Cookie)