All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.http.client.JdkHttp2ClientHttpRequestFactory Maven / Gradle / Ivy

The newest version!
package org.springframework.http.client;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.util.HttpClientUtil;
import org.zodiac.sdk.toolkit.util.collection.CollUtil;
import org.zodiac.sdk.toolkit.util.lang.ArrayUtil;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.List;
import java.util.Objects;

public class JdkHttp2ClientHttpRequestFactory implements ClientHttpRequestFactory, DisposableBean {

    private final HttpClient client;
    private final Duration readTimeout;

    public JdkHttp2ClientHttpRequestFactory(Duration readTimeout) {
        this(HttpClient.newHttpClient(), readTimeout);
    }

    public JdkHttp2ClientHttpRequestFactory(HttpClient client, Duration readTimeout) {
        this.client = Objects.requireNonNull(client, "client");
        this.readTimeout = readTimeout;
    }

    @Override
    public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) {
        return new JdkHttp2ClientHttpRequest(this.client, uri, httpMethod, readTimeout);
    }

    public static HttpRequest buildRequest(HttpHeaders headers, byte[] content, URI uri, String method,
        Duration readTimeout) {
        HttpRequest.Builder builder = HttpRequest.newBuilder(uri);
        /*headers*/
        if (CollUtil.isNotEmptyMap(headers)) {
            headers.forEach((name, list) -> {
                if (HttpClientUtil.allowed(name)) {
                    list.forEach(value -> builder.header(name, value));
                }
            });
            headers.computeIfAbsent("Accept", key -> List.of("*/*"));
        }
        /*method and content*/
        if (ArrayUtil.isNotEmptyArray(content)) {
            builder.method(method, HttpRequest.BodyPublishers.ofByteArray(content));
        } else {
            builder.method(method, HttpRequest.BodyPublishers.noBody());
        }
        if (null != readTimeout) {
            builder.timeout(readTimeout);
        }
        /*request*/
        return builder.build();
    }

    @Override
    public void destroy() throws Exception {
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy