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

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

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

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.util.HttpClientUtil;

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

public class JdkHttpClientHttpRequestFactory implements ClientHttpRequestFactory {

    private final HttpClient client;
    private final Duration readTimeout;

    public JdkHttpClientHttpRequestFactory(HttpClient client, Duration readTimeout) {
        this.client = client;
        this.readTimeout = readTimeout;
    }

    @Override
    public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) {
        return new HttpClientClientHttpRequest(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*/
        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 (content.length > 0) {
            builder.method(method, HttpRequest.BodyPublishers.ofByteArray(content));
        } else {
            builder.method(method, HttpRequest.BodyPublishers.noBody());
        }
        /*request*/
        return builder.timeout(readTimeout).build();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy