Search in sources :

Example 1 with ForestCookie

use of com.dtflys.forest.http.ForestCookie in project forest by dromara.

the class TestCookieClient method testCookieWithCallback.

@Test
public void testCookieWithCallback() {
    server.enqueue(new MockResponse().setResponseCode(200).setBody(EXPECTED).setHeader(HttpHeaders.ACCEPT, "text/plain").setHeader("Set-Cookie", "cookie_foo=cookie_bar"));
    AtomicReference<ForestCookie> cookieAtomic = new AtomicReference<>(null);
    cookieClient.testLoginWithCallback((request, cookies) -> cookieAtomic.set(cookies.allCookies().get(0)));
    ForestCookie cookie = cookieAtomic.get();
    assertThat(cookie).isNotNull().extracting(ForestCookie::getDomain, ForestCookie::getPath, ForestCookie::getName, ForestCookie::getValue).contains("localhost", "/", "cookie_foo", "cookie_bar");
    mockRequest(server).assertMethodEquals("POST").assertPathEquals("/login");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(EXPECTED).setHeader(HttpHeaders.ACCEPT, "text/plain"));
    assertThat(cookieClient.testCookieWithCallback((request, cookies) -> {
        cookies.addCookie(cookie);
    })).isNotNull().extracting(ForestResponse::getStatusCode, ForestResponse::getResult).contains(200, EXPECTED);
    mockRequest(server).assertMethodEquals("POST").assertPathEquals("/test").assertHeaderEquals("Cookie", "cookie_foo=cookie_bar");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ForestCookie(com.dtflys.forest.http.ForestCookie) Test(org.junit.Test)

Example 2 with ForestCookie

use of com.dtflys.forest.http.ForestCookie in project forest by dromara.

the class CookieTest method testCreateCookieFromOkHttp.

@Test
public void testCreateCookieFromOkHttp() {
    Duration maxAge = Duration.ofSeconds(0L);
    String url = "http://forest.dtflyx.com/docs";
    String setCookie = "foo=bar; max-age=" + maxAge.getSeconds();
    HttpUrl httpUrl = HttpUrl.parse(url);
    long currentTime = System.currentTimeMillis();
    Cookie okCookie = Cookie.parse(httpUrl, setCookie);
    ForestCookie cookie = ForestCookie.createFromOkHttpCookie(currentTime, okCookie);
    assertThat(cookie).isNotNull();
    assertThat(cookie.getName()).isEqualTo("foo");
    assertThat(cookie.getValue()).isEqualTo("bar");
    assertThat(cookie.getMaxAge().getSeconds()).isEqualTo(0);
    long expiresTime = cookie.getCreateTime().getTime() + cookie.getMaxAge().toMillis();
    assertThat(cookie.getExpiresTime()).isEqualTo(expiresTime);
    assertThat(cookie.getDomain()).isEqualTo("forest.dtflyx.com");
    assertThat(cookie.getPath()).isEqualTo("/");
    assertThat(cookie.isPersistent()).isTrue();
    assertThat(cookie.isSecure()).isFalse();
    assertThat(cookie.isHostOnly()).isTrue();
    assertThat(cookie.isHttpOnly()).isFalse();
}
Also used : Cookie(okhttp3.Cookie) ForestCookie(com.dtflys.forest.http.ForestCookie) Duration(java.time.Duration) HttpUrl(okhttp3.HttpUrl) ForestCookie(com.dtflys.forest.http.ForestCookie) Test(org.junit.Test)

Example 3 with ForestCookie

use of com.dtflys.forest.http.ForestCookie in project forest by dromara.

the class CookieTest method testCreateCookieFromHttpclient.

@Test
public void testCreateCookieFromHttpclient() {
    Duration maxAge = Duration.ofSeconds(0L);
    long currentTime = System.currentTimeMillis();
    long expiresTime = currentTime + maxAge.toMillis();
    BasicClientCookie2 httpCookie = new BasicClientCookie2("foo", "bar");
    httpCookie.setDomain("forest.dtflyx.com");
    httpCookie.setExpiryDate(new Date(expiresTime));
    httpCookie.setPath("/");
    httpCookie.setSecure(false);
    httpCookie.setDiscard(true);
    ForestCookie cookie = ForestCookie.createFromHttpclientCookie(httpCookie);
    assertThat(cookie).isNotNull();
    assertThat(cookie.getName()).isEqualTo("foo");
    assertThat(cookie.getValue()).isEqualTo("bar");
    assertThat(cookie.getMaxAge().getSeconds()).isEqualTo(0);
    assertThat(cookie.getDomain()).isEqualTo("forest.dtflyx.com");
    assertThat(cookie.getPath()).isEqualTo("/");
    assertThat(cookie.isPersistent()).isFalse();
    assertThat(cookie.isSecure()).isFalse();
}
Also used : BasicClientCookie2(org.apache.http.impl.cookie.BasicClientCookie2) Duration(java.time.Duration) Date(java.util.Date) ForestCookie(com.dtflys.forest.http.ForestCookie) Test(org.junit.Test)

Example 4 with ForestCookie

use of com.dtflys.forest.http.ForestCookie in project forest by dromara.

the class CookieTest method testMatchDomain.

@Test
public void testMatchDomain() {
    Date date = new Date();
    Duration maxAge = Duration.ofMillis(1000L);
    String domain = "localhost";
    String path = "/";
    boolean secure = true;
    boolean httpOnly = false;
    boolean hostOnly = true;
    boolean persistent = false;
    ForestCookie cookie = new ForestCookie("foo", "bar", date, maxAge, domain, path, secure, httpOnly, hostOnly, persistent);
    assertThat(cookie.matchDomain("localhost")).isTrue();
    assertThat(cookie.matchDomain("baidu.com")).isFalse();
    domain = "forest.dtflyx.com";
    cookie = new ForestCookie("foo", "bar", date, maxAge, domain, path, secure, httpOnly, hostOnly, persistent);
    assertThat(cookie.matchDomain("forest.dtflyx.com")).isTrue();
    assertThat(cookie.matchDomain("dtflyx.com")).isTrue();
}
Also used : Duration(java.time.Duration) Date(java.util.Date) ForestCookie(com.dtflys.forest.http.ForestCookie) Test(org.junit.Test)

Example 5 with ForestCookie

use of com.dtflys.forest.http.ForestCookie in project forest by dromara.

the class OkHttp3ConnectionManager method getClient.

public OkHttpClient getClient(ForestRequest request, LifeCycleHandler lifeCycleHandler) {
    Integer timeout = request.getTimeout();
    Integer connectTimeout = request.connectTimeout();
    Integer readTimeout = request.readTimeout();
    if (TimeUtils.isNone(connectTimeout)) {
        connectTimeout = timeout;
    }
    if (TimeUtils.isNone(readTimeout)) {
        readTimeout = timeout;
    }
    OkHttpClient.Builder builder = new OkHttpClient.Builder().connectionPool(pool).dispatcher(dispatcher).connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).readTimeout(readTimeout, TimeUnit.MILLISECONDS).protocols(getProtocols(request)).followRedirects(false).followSslRedirects(false).cookieJar(new CookieJar() {

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> okCookies) {
            ForestCookies cookies = new ForestCookies();
            for (Cookie okCookie : okCookies) {
                long currentTime = System.currentTimeMillis();
                ForestCookie cookie = ForestCookie.createFromOkHttpCookie(currentTime, okCookie);
                cookies.addCookie(cookie);
            }
            lifeCycleHandler.handleSaveCookie(request, cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            ForestCookies cookies = new ForestCookies();
            lifeCycleHandler.handleLoadCookie(request, cookies);
            List<ForestCookie> forestCookies = cookies.allCookies();
            List<Cookie> okCookies = new ArrayList<>(forestCookies.size());
            for (ForestCookie cookie : forestCookies) {
                Duration maxAge = cookie.getMaxAge();
                Date createTime = cookie.getCreateTime();
                long expiresAt = createTime.getTime() + maxAge.toMillis();
                Cookie.Builder cookieBuilder = new Cookie.Builder();
                cookieBuilder.name(cookie.getName()).value(cookie.getValue()).expiresAt(expiresAt).path(cookie.getPath());
                if (cookie.isHostOnly()) {
                    cookieBuilder.hostOnlyDomain(cookie.getDomain());
                } else {
                    cookieBuilder.domain(cookie.getDomain());
                }
                if (cookie.isHttpOnly()) {
                    cookieBuilder.httpOnly();
                }
                if (cookie.isSecure()) {
                    cookieBuilder.secure();
                }
                Cookie okCookie = cookieBuilder.build();
                okCookies.add(okCookie);
            }
            return okCookies;
        }
    });
    // set proxy
    ForestProxy proxy = request.getProxy();
    if (proxy != null) {
        Proxy okProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()));
        builder.proxy(okProxy);
        if (StringUtils.isNotEmpty(proxy.getUsername())) {
            builder.proxyAuthenticator(new Authenticator() {

                @Nullable
                @Override
                public Request authenticate(@Nullable Route route, Response response) {
                    Request.Builder proxyBuilder = response.request().newBuilder();
                    String credential = Credentials.basic(proxy.getUsername(), proxy.getPassword());
                    proxyBuilder.addHeader("Proxy-Authorization", credential);
                    return proxyBuilder.build();
                }
            });
        }
    }
    if (request.isSSL()) {
        SSLSocketFactory sslSocketFactory = request.getSSLSocketFactory();
        builder.sslSocketFactory(sslSocketFactory, getX509TrustManager(request)).hostnameVerifier(request.hostnameVerifier());
    }
    // add default interceptor
    builder.addNetworkInterceptor(chain -> {
        Response response = chain.proceed(chain.request());
        return response.newBuilder().body(new OkHttpResponseBody(request, response.body(), lifeCycleHandler)).build();
    });
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) InetSocketAddress(java.net.InetSocketAddress) ForestCookie(com.dtflys.forest.http.ForestCookie) ForestProxy(com.dtflys.forest.http.ForestProxy) Proxy(java.net.Proxy) OkHttpResponseBody(com.dtflys.forest.backend.okhttp3.response.OkHttpResponseBody) ArrayList(java.util.ArrayList) List(java.util.List) CookieJar(okhttp3.CookieJar) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) ForestProxy(com.dtflys.forest.http.ForestProxy) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route) Cookie(okhttp3.Cookie) ForestCookie(com.dtflys.forest.http.ForestCookie) ForestRequest(com.dtflys.forest.http.ForestRequest) Request(okhttp3.Request) Duration(java.time.Duration) HttpUrl(okhttp3.HttpUrl) Date(java.util.Date) Response(okhttp3.Response) ForestCookies(com.dtflys.forest.http.ForestCookies) Nullable(javax.annotation.Nullable)

Aggregations

ForestCookie (com.dtflys.forest.http.ForestCookie)10 Duration (java.time.Duration)7 Test (org.junit.Test)7 Date (java.util.Date)6 ForestCookies (com.dtflys.forest.http.ForestCookies)3 Cookie (okhttp3.Cookie)2 HttpUrl (okhttp3.HttpUrl)2 OkHttpResponseBody (com.dtflys.forest.backend.okhttp3.response.OkHttpResponseBody)1 ForestProxy (com.dtflys.forest.http.ForestProxy)1 ForestRequest (com.dtflys.forest.http.ForestRequest)1 InetSocketAddress (java.net.InetSocketAddress)1 Proxy (java.net.Proxy)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Nullable (javax.annotation.Nullable)1 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)1 Authenticator (okhttp3.Authenticator)1 CookieJar (okhttp3.CookieJar)1 OkHttpClient (okhttp3.OkHttpClient)1