Search in sources :

Example 46 with ForestRequest

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

the class TestRequest method testDefaultRequest.

@Test
public void testDefaultRequest() {
    ObjectUtil.isBasicType(Object.class);
    ForestConfiguration configuration = ForestConfiguration.createConfiguration();
    ForestRequest request = new ForestRequest(configuration);
    assertEquals(configuration, request.getConfiguration());
    assertEquals(configuration.getTimeout().intValue(), request.getTimeout());
    assertEquals(0, request.getRetryCount());
}
Also used : ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) ForestRequest(com.dtflys.forest.http.ForestRequest) Test(org.junit.Test)

Example 47 with ForestRequest

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

the class TestRequest method testInterceptorAttribute.

@Test
public void testInterceptorAttribute() {
    ForestConfiguration configuration = ForestConfiguration.createConfiguration();
    ForestRequest request = new ForestRequest(configuration);
    request.addInterceptorAttribute(BasicAuthClient.class, "Xxx", "foo");
    request.addInterceptorAttribute(BasicAuthClient.class, "Yyy", "bar");
    Object xxxValue = request.getInterceptorAttribute(BasicAuthClient.class, "Xxx");
    assertNotNull(xxxValue);
    assertEquals("foo", xxxValue);
    Object yyyValue = request.getInterceptorAttribute(BasicAuthClient.class, "Yyy");
    assertNotNull(yyyValue);
    assertEquals("bar", yyyValue);
    Map<String, Object> attrMap = new HashMap<>();
    attrMap.put("Xxx", "xxxx");
    attrMap.put("Zzz", 1111);
    InterceptorAttributes attributes = new InterceptorAttributes(BasicAuthClient.class, attrMap);
    request.addInterceptorAttributes(BasicAuthClient.class, attributes);
    xxxValue = request.getInterceptorAttribute(BasicAuthClient.class, "Xxx");
    assertNotNull(xxxValue);
    assertEquals("xxxx", xxxValue);
    Object zzzValue = request.getInterceptorAttribute(BasicAuthClient.class, "Zzz");
    assertNotNull(zzzValue);
    assertEquals(Integer.valueOf(1111), zzzValue);
}
Also used : ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) InterceptorAttributes(com.dtflys.forest.interceptor.InterceptorAttributes) HashMap(java.util.HashMap) BasicAuthClient(com.dtflys.test.interceptor.BasicAuthClient) ForestRequest(com.dtflys.forest.http.ForestRequest) Test(org.junit.Test)

Example 48 with ForestRequest

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

the class TestRequest method testAttachment.

@Test
public void testAttachment() {
    ForestConfiguration configuration = ForestConfiguration.createConfiguration();
    ForestRequest request = new ForestRequest(configuration);
    request.addAttachment("Xxx", "foo");
    request.addAttachment("Yyy", "bar");
    Object xxxValue = request.getAttachment("Xxx");
    Object yyyValue = request.getAttachment("Yyy");
    assertEquals("foo", xxxValue);
    assertEquals("bar", yyyValue);
    request.addAttachment("Yyy", "1111");
    yyyValue = request.getAttachment("Yyy");
    assertEquals("1111", yyyValue);
}
Also used : ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) ForestRequest(com.dtflys.forest.http.ForestRequest) Test(org.junit.Test)

Example 49 with ForestRequest

use of com.dtflys.forest.http.ForestRequest 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)

Example 50 with ForestRequest

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

the class TestUploadClient method testMixtureUploadImageWithJSONBodyParams.

@Test
public void testMixtureUploadImageWithJSONBodyParams() throws InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    String path = Objects.requireNonNull(this.getClass().getResource("/test-img.jpg")).getPath();
    if (path.startsWith("/") && isWindows()) {
        path = path.substring(1);
    }
    File file = new File(path);
    Map<String, Object> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 2);
    ForestRequest request = uploadClient.imageUploadWithJSONBodyParams("img1.jpg", file, map);
    assertNotNull(request);
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(1, multipartList.size());
    ForestMultipart multipart = multipartList.get(0);
    // assertTrue(Map.class.isAssignableFrom(request.getMethod().getReturnClass()));
    assertTrue(multipart instanceof FileMultipart);
    assertEquals("file", multipart.getName());
    assertEquals("img1.jpg", multipart.getOriginalFileName());
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file", multiparts -> {
        assertEquals(1, multiparts.size());
        FileItem fileItem = multiparts.get(0);
        assertEquals("img1.jpg", fileItem.getName());
        assertEquals("image/jpeg", fileItem.getContentType());
    }).assertMultipart("params", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("application/json", contentType.toStringWithoutParameters());
        try {
            assertEquals(JSON.toJSONString(map), IOUtils.toString(item.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ContentType(com.dtflys.forest.backend.ContentType) ForestRequest(com.dtflys.forest.http.ForestRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assert.assertThat(org.junit.Assert.assertThat) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) InputStreamMultipart(com.dtflys.forest.multipart.InputStreamMultipart) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) MockWebServer(okhttp3.mockwebserver.MockWebServer) LinkedList(java.util.LinkedList) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) Assert.assertNotNull(org.junit.Assert.assertNotNull) FileItem(org.apache.commons.fileupload.FileItem) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ByteArrayMultipart(com.dtflys.forest.multipart.ByteArrayMultipart) File(java.io.File) Objects(java.util.Objects) UploadClient(com.dtflys.test.http.client.UploadClient) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) JSON(com.alibaba.fastjson.JSON) Rule(org.junit.Rule) MockServerRequest(com.dtflys.forest.mock.MockServerRequest) StringUtils(com.dtflys.forest.utils.StringUtils) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) FileUploadException(org.apache.commons.fileupload.FileUploadException) MockResponse(okhttp3.mockwebserver.MockResponse) HttpBackend(com.dtflys.forest.backend.HttpBackend) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) MockResponse(okhttp3.mockwebserver.MockResponse) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ContentType(com.dtflys.forest.backend.ContentType) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) ForestRequest(com.dtflys.forest.http.ForestRequest) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) File(java.io.File) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Test(org.junit.Test)

Aggregations

ForestRequest (com.dtflys.forest.http.ForestRequest)85 Test (org.junit.Test)75 MockResponse (okhttp3.mockwebserver.MockResponse)59 BaseClientTest (com.dtflys.test.http.BaseClientTest)48 HttpBackend (com.dtflys.forest.backend.HttpBackend)42 MockWebServer (okhttp3.mockwebserver.MockWebServer)42 Rule (org.junit.Rule)42 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)39 ForestResponse (com.dtflys.forest.http.ForestResponse)37 CountDownLatch (java.util.concurrent.CountDownLatch)36 BeforeClass (org.junit.BeforeClass)36 MockServerRequest.mockRequest (com.dtflys.forest.mock.MockServerRequest.mockRequest)35 AssertionsForClassTypes.assertThat (org.assertj.core.api.AssertionsForClassTypes.assertThat)35 TimeUnit (java.util.concurrent.TimeUnit)29 AtomicReference (java.util.concurrent.atomic.AtomicReference)29 ContentType (com.dtflys.forest.backend.ContentType)15 File (java.io.File)14 URL (java.net.URL)14 HashMap (java.util.HashMap)14 LinkedHashMap (java.util.LinkedHashMap)14