Files
2026-10-15 16:35:05 +02:00

44 lines
1.7 KiB
Java

package org.gingercal;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
/** Desktop-only transport used to test the CalDAV core against a real server. */
public class JdkHttp implements Http {
final HttpClient c = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER)
.connectTimeout(Duration.ofSeconds(10)).build();
public int requests;
public Resp exec(String method, String url, String[] headers, String body, String contentType)
throws IOException {
requests++;
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(url))
.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(body));
for (int i = 0; i + 1 < headers.length; i += 2) b.header(headers[i], headers[i + 1]);
if (contentType != null) b.header("Content-Type", contentType);
try {
HttpResponse<String> r;
try {
r = c.send(b.build(), HttpResponse.BodyHandlers.ofString());
} catch (IOException stale) { // test server drops idle keep-alive sockets
r = c.send(b.build(), HttpResponse.BodyHandlers.ofString());
}
Resp out = new Resp();
out.code = r.statusCode();
out.body = r.body();
out.etag = r.headers().firstValue("ETag").orElse(null);
out.location = r.headers().firstValue("Location").orElse(null);
return out;
} catch (InterruptedException e) {
throw new IOException(e);
}
}
public void close() {}
}