use of io.servicetalk.http.api.RedirectConfigBuilder 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.RedirectConfigBuilder in project servicetalk by apple.
the class ExpectContinueTest method serverRespondsWithRedirect.
@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void serverRespondsWithRedirect(HttpProtocol protocol, boolean withCL) throws Exception {
try (HttpServerContext serverContext = startServer(protocol, (ctx, request, response) -> {
if ("/redirect".equals(request.requestTarget())) {
response.status(PERMANENT_REDIRECT);
response.setHeader(LOCATION, "/");
response.sendMetaData().close();
return;
}
requestReceived.countDown();
sendContinue.await();
StringBuilder sb = new StringBuilder();
request.payloadBody().forEach(chunk -> sb.append(chunk.toString(US_ASCII)));
returnResponse.await();
try (HttpPayloadWriter<Buffer> writer = response.sendMetaData()) {
writer.write(ctx.executionContext().bufferAllocator().fromAscii(sb));
}
});
StreamingHttpClient client = createClient(serverContext, protocol, new RedirectingHttpRequesterFilter(new RedirectConfigBuilder().allowedMethods(POST).headersToRedirect(CONTENT_LENGTH, TRANSFER_ENCODING, EXPECT).redirectPayloadBody(true).build()));
StreamingHttpConnection connection = client.reserveConnection(client.get("/")).toFuture().get()) {
BufferAllocator allocator = connection.executionContext().bufferAllocator();
TestPublisher<Buffer> payload = new TestPublisher.Builder<Buffer>().singleSubscriber().build();
connection.request(newRequest(connection, withCL, false, payload).requestTarget("/redirect")).subscribe(responses::add);
requestReceived.await();
assertThat("Unexpected subscribe to payload body before 100 (Continue)", payload.isSubscribed(), is(false));
sendContinue.countDown();
sendRequestPayload(payload, allocator);
returnResponse.countDown();
assertResponse(OK, PAYLOAD + PAYLOAD);
sendFollowUpRequest(connection, withCL, allocator, OK);
}
}
use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.
the class RedirectingHttpRequesterFilterTest method shouldRedirectThrows.
@Test
void shouldRedirectThrows() {
when(httpClient.request(any())).thenReturn(redirectResponse(MOVED_PERMANENTLY), okResponse());
StreamingHttpClient client = newClient(new RedirectConfigBuilder().redirectPredicate((relative, count, request, response) -> {
throw DELIBERATE_EXCEPTION;
}).build());
ExecutionException e = assertThrows(ExecutionException.class, () -> client.request(newRequest(client, GET)).toFuture().get());
assertThat(e.getCause(), sameInstance(DELIBERATE_EXCEPTION));
}
use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.
the class RedirectingHttpRequesterFilterTest method overrideAllowedMethods.
@Test
void overrideAllowedMethods() throws Exception {
RedirectConfig config = new RedirectConfigBuilder().allowedMethods(POST).build();
testRedirected(POST, MOVED_PERMANENTLY, config);
testNoRedirectWasDone(GET, MOVED_PERMANENTLY, config);
testNoRedirectWasDone(HEAD, MOVED_PERMANENTLY, config);
}
use of io.servicetalk.http.api.RedirectConfigBuilder in project servicetalk by apple.
the class RedirectingHttpRequesterFilterTest method redirectForOnlyRelativeWithAbsoluteFormRelativeLocationWithPort.
@Test
void redirectForOnlyRelativeWithAbsoluteFormRelativeLocationWithPort() throws Exception {
when(httpClient.request(any())).thenReturn(redirectResponse(MOVED_PERMANENTLY, "http://servicetalk.io:80"), okResponse());
StreamingHttpClient client = newClient(new RedirectConfigBuilder().allowNonRelativeRedirects(false).build());
verifyRedirected(client, newRequest(client, GET).setHeader(HOST, "servicetalk.io:80"), true, false);
}
Aggregations