use of io.servicetalk.http.api.HttpClient in project servicetalk by apple.
the class ClientEffectiveStrategyTest method getResponse.
private String getResponse(ClientType clientType, StreamingHttpClient client) throws Exception {
switch(clientType) {
case Blocking:
BlockingHttpClient blockingClient = client.asBlockingClient();
return blockingClient.request(blockingClient.get("/")).payloadBody().toString(StandardCharsets.US_ASCII);
case BlockingStreaming:
BlockingStreamingHttpClient blockingStreamingClient = client.asBlockingStreamingClient();
Supplier<CompositeBuffer> supplier = client.executionContext().bufferAllocator()::newCompositeBuffer;
return StreamSupport.stream(blockingStreamingClient.request(blockingStreamingClient.get("/")).payloadBody().spliterator(), false).reduce((Buffer base, Buffer buffer) -> (base instanceof CompositeBuffer ? ((CompositeBuffer) base) : supplier.get().addBuffer(base)).addBuffer(buffer)).map(buffer -> buffer.toString(StandardCharsets.US_ASCII)).orElse("");
case AsyncStreaming:
return client.request(client.get("/")).flatMap(resp -> resp.payloadBody().collect(() -> client.executionContext().bufferAllocator().newCompositeBuffer(), CompositeBuffer::addBuffer)).toFuture().get().toString(StandardCharsets.US_ASCII);
case Async:
HttpClient httpClient = client.asClient();
return httpClient.request(httpClient.get("/")).toFuture().get().payloadBody().toString(StandardCharsets.US_ASCII);
default:
fail("Unexpected client type " + clientType);
/* NOTREACHED */
return "failed";
}
}
use of io.servicetalk.http.api.HttpClient in project servicetalk by apple.
the class MultiAddressUrlRedirectClient method main.
public static void main(String... args) throws Exception {
try (HttpClient client = HttpClients.forMultiAddressUrl().followRedirects(new RedirectConfigBuilder().maxRedirects(3).allowNonRelativeRedirects(true).allowedMethods(GET, POST).redirectPredicate((relative, redirectCount, prevRequest, redirectResponse) -> // allow only relative redirects
relative || // OR non-relative redirects to a trusted server:
redirectResponse.headers().get(LOCATION, "").toString().startsWith("https://localhost:" + SECURE_SERVER_PORT)).headersToRedirect(CUSTOM_HEADER).redirectPayloadBody(true).redirectRequestTransformer((relative, prevRequest, redirectResponse, redirectedRequest) -> {
// prevRequest and redirectResponse: check/copy other headers, modify request method, etc.
return redirectedRequest;
}).build()).initializer((scheme, address, builder) -> {
// already provides default SSL configuration and this step may be skipped.
if ("https".equalsIgnoreCase(scheme)) {
builder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build());
}
}).build()) {
final String serverThatRedirects = "http://localhost:" + NON_SECURE_SERVER_PORT;
System.out.println("- Simple GET request:");
client.request(client.get(serverThatRedirects + "/relative")).whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerAscii()));
System.out.println();
}).toFuture().get();
System.out.println("- Relative redirect for POST request with headers and payload body:");
client.request(client.post(serverThatRedirects + "/relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerAscii()));
System.out.println();
}).toFuture().get();
System.out.println("- Non-relative redirect for POST request with headers and payload body:");
client.request(client.post(serverThatRedirects + "/non-relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerAscii()));
System.out.println();
}).toFuture().get();
}
}
use of io.servicetalk.http.api.HttpClient in project servicetalk by apple.
the class RetryUrlClient method main.
public static void main(String[] args) throws Exception {
try (HttpClient client = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> {
builder.appendClientFilter(new RetryingHttpRequesterFilter.Builder().responseMapper(httpResponseMetaData -> SERVER_ERROR_5XX.contains(httpResponseMetaData.status()) ? // Response status is 500-599, we request a retry
new RetryingHttpRequesterFilter.HttpResponseException("Retry 5XX", httpResponseMetaData) : // Not a 5XX response, we do not know whether retry is required
null).retryResponses((meta, error) -> RetryingHttpRequesterFilter.BackOffPolicy.ofImmediate(2)).build());
}).build()) {
client.request(client.get("http://localhost:8080/sayHello")).whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(textSerializerUtf8()));
}).toFuture().get();
}
}
use of io.servicetalk.http.api.HttpClient in project servicetalk by apple.
the class PojoClient method main.
public static void main(String[] args) throws Exception {
try (HttpClient client = HttpClients.forSingleAddress("localhost", 8080).build()) {
client.request(client.post("/pojos").payloadBody(new CreatePojoRequest("value"), REQ_SERIALIZER)).whenOnSuccess(resp -> {
System.out.println(resp.toString((name, value) -> value));
System.out.println(resp.payloadBody(RESP_SERIALIZER));
}).toFuture().get();
}
}
use of io.servicetalk.http.api.HttpClient in project servicetalk by apple.
the class ExpectContinueTest method retryExpectationFailedAggregated.
@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void retryExpectationFailedAggregated(HttpProtocol protocol, boolean withCL) throws Exception {
try (HttpServerContext serverContext = startServer(protocol);
HttpClient client = createClient(serverContext, protocol, new RetryingHttpRequesterFilter.Builder().retryExpectationFailed(true).build()).asClient()) {
Future<HttpResponse> responseFuture = client.request(newRequest(client, withCL, true, PAYLOAD + PAYLOAD, client.executionContext().bufferAllocator())).toFuture();
requestReceived.await();
sendContinue.countDown();
returnResponse.countDown();
HttpResponse response = responseFuture.get();
assertThat(response.status(), is(OK));
assertThat(response.payloadBody().toString(US_ASCII), equalTo(PAYLOAD + PAYLOAD));
}
}
Aggregations