org.springframework.http.client.HttpClientClientHttpRequest Maven / Gradle / Ivy
The newest version!
package org.springframework.http.client;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class HttpClientClientHttpRequest extends AbstractClientHttpRequest {
private final HttpClient client;
private final URI uri;
private final HttpMethod method;
private final Duration readTimeout;
private ByteArrayOutputStream bufferedOutput = new ByteArrayOutputStream(1024);
public HttpClientClientHttpRequest(HttpClient client, URI uri, HttpMethod method, Duration readTimeout) {
this.client = client;
this.uri = uri;
this.method = method;
this.readTimeout = readTimeout;
}
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
return this.bufferedOutput;
}
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
byte[] content = this.bufferedOutput.toByteArray();
HttpRequest request =
JdkHttpClientHttpRequestFactory.buildRequest(headers, content, getURI(), getMethodValue(), readTimeout);
try {
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
return new HttpClientHttpResponse(response);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
} finally {
this.bufferedOutput = new ByteArrayOutputStream(0);
}
}
@Override
public String getMethodValue() {
return this.method.name();
}
@Override
public URI getURI() {
return this.uri;
}
}