Post

Configure Timeouts, Redirects and Charsets in REST Assured

Configure how the HTTP client behaves with RestAssuredConfig, covering read and connect timeouts with the Duration methods of REST Assured 6.3, following redirects for GET, POST and all methods, and the default charset for decoding text.

Configure Timeouts, Redirects and Charsets in REST Assured

A stuck downstream service hangs your whole build for minutes, because no test sets a timeout. A login test can’t check the 302 it’s about, because REST Assured followed it. And a greeting test passes on your laptop but fails on a CI agent with GrüÃe uit Zürich. In this guide, you’ll configure how the HTTP client behaves, with timeouts, redirect rules and a default charset, so tests don’t depend on defaults or on the machine they run on.

Level: Intermediate · Time: 20 minutes · Part of: Module 5: Reusable Specifications and Configuration, section 3

What You’ll Build

You’ll build a test class called ClientConfigurationTest with eight tests. Two set timeouts, four control how redirects are followed, and two set the charset used to decode text.

One of the tests checks a redirect instead of following it:

1
2
3
4
5
GET /test-support/redirect HTTP/1.1
Host: localhost:<port>

HTTP/1.1 302 Found
Location: /test-support/landing

When you’re done, Maven reports eight passing tests:

1
2
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Set timeouts.
  • Control redirects.
  • Set the charset for decoding text.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create ClientConfigurationTest in a new section_03 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (ClientConfigurationTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Build Reusable Request Specifications in REST Assured.

Out of scope: this guide doesn’t cover TLS, proxies or authentication settings; they’re taught in Module 7.

Understand RestAssuredConfig

The problem. The HTTP client’s defaults answer three questions for you: how long to wait for a server, whether to follow a redirect, and which charset to decode text with when the server doesn’t say. Most of the time the answers are fine. But a suite that hangs on a stuck service, can’t see the redirect it’s testing, or decodes differently on CI has a configuration problem.

The concept. RestAssuredConfig groups many smaller configs, one per topic. You’ve used HeaderConfig, EncoderConfig, JsonConfig and ObjectMapperConfig already. This guide adds three:

ConfigControls
HttpClientConfigConnect and read timeouts
RedirectConfigWhether, and for which methods, redirects are followed
DecoderConfigHow the response is decoded, including the charset

A config is immutable: each call such as config().httpClient(..) returns a new one. You can set it per request with config(..), in a specification with setConfig(..) on a RequestSpecBuilder, or globally in RestAssured.config, with the usual warnings about static state.

When to use each. Set a read timeout in every shared specification, with a generous margin, so a stuck service fails fast instead of hanging the build. Turn redirect following off when the redirect is what you test. Set the decoding charset whenever an API sends text without declaring one.

Configure the client explicitly, so a test behaves the same on every machine.

Meet the API Under Test

The Open Banking API has a few endpoints under /test-support that exist only to exercise client configuration. They have none of the rules of the real API:

RequestResponse
GET /test-support/slow?millis=..Waits that many milliseconds, then answers 200 with {"sleptMillis": ..}
GET or POST /test-support/redirect302 Found with Location: /test-support/landing
GET or POST /test-support/landing{"method": ".."}, the method that arrived
GET /test-support/greetingGrüße uit Zürich as UTF-8, with the content type text/plain and no charset

Your tests check these values:

  • Whether a request to /slow finishes or times out.
  • The status, Location and method of a redirect, followed or not.
  • The decoded text of /greeting.

Set Timeouts

Set Up the Test Class

Goal: create the test class with a helper for the test-support endpoints, and one that finds an exception in a chain of causes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.javanibble.module_05.section_03;

import static io.restassured.RestAssured.given;
import static io.restassured.config.DecoderConfig.decoderConfig;
import static io.restassured.config.HttpClientConfig.httpClientConfig;
import static io.restassured.config.RedirectConfig.redirectConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.javanibble.openbanking.OpenBankingApi;

import io.restassured.specification.RequestSpecification;

import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class ClientConfigurationTest {

    private static OpenBankingApi api;

    @BeforeAll
    static void startApi() {
        api = OpenBankingApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification testSupport() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath("/test-support");
    }

    private static void assertCauseIs(Class<? extends Throwable> expected, Throwable thrown) {
        for (Throwable t = thrown; t != null; t = t.getCause()) {
            if (expected.isInstance(t)) {
                return;
            }
        }
        throw new AssertionError("Expected a " + expected.getSimpleName() + " in the causes of " + thrown, thrown);
    }
}

What’s happening:

  • testSupport() points requests at /test-support, which needs no token or interaction id.
  • assertCauseIs(..) walks an exception’s chain of causes, so the timeout test doesn’t depend on whether the exception is thrown directly or wrapped.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Stop Waiting for a Slow Server

Goal: give up on a server that takes two seconds, after 300 milliseconds.

1
2
3
4
5
6
7
8
9
10
11
@Test
void aReadTimeoutStopsWaitingForASlowServer() {
    Exception exception = assertThrows(Exception.class, () ->
        testSupport()
            .config(config().httpClient(httpClientConfig().readTimeout(Duration.ofMillis(300))))
            .queryParam("millis", 2000)
        .when()
            .get("/slow"));

    assertCauseIs(SocketTimeoutException.class, exception);
}

What’s happening:

  • readTimeout(Duration.ofMillis(300)) limits how long the client waits for data once connected.
  • The server waits two seconds, so the client gives up with java.net.SocketTimeoutException: Read timed out.
  • A timeout isn’t an assertion failure, so it’s caught with assertThrows(..), and assertCauseIs(..) checks its type.

Checkpoint: run ClientConfigurationTest from your IDE. One test runs and passes. It takes about two seconds, because the server finishes its sleep after the client has given up.

Set Timeouts That Are Long Enough

Goal: set both timeouts with a generous margin, and see a normal request pass.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void withinTheTimeoutAllIsWell() {
    testSupport()
        .config(config().httpClient(httpClientConfig()
                .connectTimeout(Duration.ofSeconds(2))
                .readTimeout(Duration.ofSeconds(5))))
        .queryParam("millis", 100)
    .when()
        .get("/slow")
    .then()
        .statusCode(200);
}

What’s happening:

  • connectTimeout(..) limits how long the client waits to open the connection, and readTimeout(..) how long it waits for data.
  • The server answers after 100 milliseconds, well within both limits.

Checkpoint: run the class again. Two tests pass.

Use the Duration methods. They arrived in REST Assured 6.3, and replace setting Apache HttpClient 4 parameters by name, which REST Assured 7 removes. Keep margins generous, too: a limit that passes on your laptop fails on a busy CI agent.

Control Redirects

Follow a GET Redirect

Goal: show that a GET redirect is followed by default.

1
2
3
4
@Test
void getRedirectsAreFollowedByDefault() {
    testSupport().when().get("/redirect").then().statusCode(200).body("method", equalTo("GET"));
}

What’s happening:

  • The server answers 302, REST Assured follows the Location, and the test sees the landing page, not the redirect.

Checkpoint: run the class again. Three tests pass.

Turn Following Off

Goal: check the redirect itself.

1
2
3
4
5
6
7
8
9
10
@Test
void followingCanBeTurnedOff() {
    testSupport()
        .redirects().follow(false)
    .when()
        .get("/redirect")
    .then()
        .statusCode(302)
        .header("Location", "/test-support/landing");
}

What’s happening:

  • redirects().follow(false) is a shortcut for redirectConfig().followRedirects(false).
  • Now the test sees the 302 and its Location. Turn following off whenever the redirect is what you test, such as after a login or for a moved resource.

Checkpoint: run the class again. Four tests pass.

See a POST Redirect Not Followed

Goal: show that a POST redirect isn’t followed by default.

1
2
3
4
@Test
void postRedirectsAreNotFollowedByDefault() {
    testSupport().when().post("/redirect").then().statusCode(302);
}

What’s happening:

  • By default, REST Assured follows a GET redirect but not a POST redirect, so this test sees the 302.

Checkpoint: run the class again. Five tests pass.

Follow Redirects for All Methods

Goal: follow a POST redirect too.

1
2
3
4
5
6
7
8
9
@Test
void followRedirectsForAllMethods() {
    testSupport()
        .config(config().redirect(redirectConfig().followRedirectsForAllMethods(true)))
    .when()
        .post("/redirect")
    .then()
        .statusCode(200);
}

What’s happening:

  • followRedirectsForAllMethods(true), new in REST Assured 6.3, follows redirects of POST, PUT and DELETE too.
  • A 302 after a POST is followed with a GET, as browsers do: the landing page answers {"method":"GET"}.

Checkpoint: run the class again. Six tests pass.

Set the Charset for Decoding Text

The greeting endpoint sends Grüße uit Zürich encoded as UTF-8, but its content type is only text/plain, so the client has to guess the charset. REST Assured’s guess is DecoderConfig’s default content charset, which is the JVM’s default charset.

See the Wrong Guess

Goal: decode the greeting as ISO-8859-1, and see the umlauts break.

1
2
3
4
5
6
7
8
9
10
@Test
void withoutACharsetTextIsDecodedWithTheDefaultContentCharset() {
    testSupport()
        .config(config().decoderConfig(decoderConfig().defaultContentCharset("ISO-8859-1")))
    .when()
        .get("/greeting")
    .then()
        .body(not(equalTo("Grüße uit Zürich")))
        .body(equalTo(new String("Grüße uit Zürich".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
}

What’s happening:

  • defaultContentCharset("ISO-8859-1") sets the guess to HTTP’s old default for text.
  • Each two-byte UTF-8 character becomes two characters, and the body reads GrüÃe uit Zürich, with an invisible control character after the second Ã.
  • The second check builds that exact wrong string, so the test proves how the text was decoded.

Checkpoint: run the class again. Seven tests pass.

Make the Charset Explicit

Goal: decode the greeting correctly, whatever the JVM’s default is.

1
2
3
4
5
6
7
8
9
@Test
void decoderConfigSetsTheDefaultCharset() {
    testSupport()
        .config(config().decoderConfig(decoderConfig().defaultContentCharset("UTF-8")))
    .when()
        .get("/greeting")
    .then()
        .body(equalTo("Grüße uit Zürich"));
}

What’s happening:

  • defaultContentCharset("UTF-8") makes the guess explicit, so the greeting decodes correctly.
  • The setting is used only when the server doesn’t declare a charset.

Checkpoint: run the class again. All eight tests pass.

Don’t rely on the JVM’s default charset. Since JDK 18 it’s UTF-8, so the default guess is right on a stock JVM, but that’s luck, not design: an older JVM, a -Dfile.encoding setting on a CI agent, or a platform default can change it. The real fix is on the server: send text/plain; charset=utf-8.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-05 -Dtest=ClientConfigurationTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_05.section_03.ClientConfigurationTest
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.387 s -- in com.javanibble.module_05.section_03.ClientConfigurationTest
[INFO]
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

The class takes about two seconds, almost all of it spent in the timeout test.

Make a Test Fail

In aReadTimeoutStopsWaitingForASlowServer, change Duration.ofMillis(300) to Duration.ofSeconds(5) and run the command again. You should see a result similar to the following:

1
2
[ERROR] Failures:
[ERROR]   ClientConfigurationTest.aReadTimeoutStopsWaitingForASlowServer:59 Expected java.lang.Exception to be thrown, but nothing was thrown.

With a five-second limit, the two-second server is within the timeout, so the request succeeds and nothing is thrown. The message comes from JUnit’s assertThrows(..). Notice that the test now takes the full two seconds and passes the request: a timeout that’s too generous for what you test hides the slow server you meant to catch.

Change Duration.ofSeconds(5) back to Duration.ofMillis(300) and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
java.net.SocketTimeoutException: Read timed outThe server took longer than the read timeoutRaise the limit, or investigate the slow server
A test hangs for minutesNo read timeout is setSet readTimeout(Duration) in a shared specification
A test sees 200 where it expected a 302A GET redirect was followedUse redirects().follow(false)
A test sees 302 after a POSTPOST redirects aren’t followed by defaultUse followRedirectsForAllMethods(true)
Text such as GrüÃe instead of GrüßeThe text was decoded with the wrong charsetSet decoderConfig().defaultContentCharset("UTF-8")

Try It Yourself

Exercise 1: Put a Timeout in a Specification

Add a test called aSpecificationCarriesTheTimeouts. Build a request specification for /test-support with setConfig(..), using a connect timeout of two seconds and a read timeout of one second. With it, check that a request to /slow with millis=200 answers 200, and that one with millis=1500 throws.

Hint

Use RequestSpecBuilder, as in Build Reusable Request Specifications in REST Assured, with setBaseUri(..), setPort(..), setBasePath(..) and setConfig(..). Catch the timeout with assertThrows(..).

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void aSpecificationCarriesTheTimeouts() {
    RequestSpecification patient = new RequestSpecBuilder()
        .setBaseUri(api.baseUri())
        .setPort(api.port())
        .setBasePath("/test-support")
        .setConfig(config().httpClient(httpClientConfig()
                .connectTimeout(Duration.ofSeconds(2))
                .readTimeout(Duration.ofSeconds(1))))
        .build();

    given(patient).queryParam("millis", 200).when().get("/slow").then().statusCode(200);

    assertThrows(Exception.class, () -> given(patient).queryParam("millis", 1500).when().get("/slow"));
}

Add import io.restassured.builder.RequestSpecBuilder; to the class.

Exercise 2: Build a Browser-Like Specification

Add a test called aBrowserLikeSpecification. Build a specification for /test-support whose config follows redirects for all methods and decodes text as UTF-8. With it, check that a POST to /redirect ends on the landing page as a GET; that the same request with redirects().follow(false) sees the 302 and its Location; and that the greeting decodes correctly.

Hint

Chain the two settings on one config: config().redirect(..).decoderConfig(..). A request can still change one setting of its specification, such as redirects().follow(false).

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
void aBrowserLikeSpecification() {
    RequestSpecification browserLike = new RequestSpecBuilder()
        .setBaseUri(api.baseUri())
        .setPort(api.port())
        .setBasePath("/test-support")
        .setConfig(config()
                .redirect(redirectConfig().followRedirectsForAllMethods(true))
                .decoderConfig(decoderConfig().defaultContentCharset("UTF-8")))
        .build();

    given(browserLike).when().post("/redirect").then().statusCode(200).body("method", equalTo("GET"));

    given(browserLike)
        .redirects().follow(false)
    .when()
        .post("/redirect")
    .then()
        .statusCode(302)
        .header("Location", "/test-support/landing");

    given(browserLike).when().get("/greeting").then().body(equalTo("Grüße uit Zürich"));
}

Summary

You built ClientConfigurationTest, which sets timeouts, controls how redirects are followed, and sets the charset used to decode text. A stuck service now fails fast, the login redirect can be checked, and the greeting reads the same on every machine.

  • RestAssuredConfig groups the client’s settings, and can be set per request, in a specification with setConfig(..), or globally.
  • HttpClientConfig sets connect and read timeouts with Duration methods since REST Assured 6.3; leave generous margins.
  • GET redirects are followed by default and POST redirects aren’t; followRedirectsForAllMethods(true) follows all, as a GET.
  • redirects().follow(false) lets a test check the redirect itself: its status and Location.
  • DecoderConfig.defaultContentCharset(..) sets the charset for text without a declared one, so tests don’t depend on the JVM’s default.

Here are the commands you used in this guide:

1
mvn test -pl module-05 -Dtest=ClientConfigurationTest

What’s Next

Next: continue with Keep Secrets Out of REST Assured Logs, which masks the Authorization and Cookie headers in every log, including logs written on failure.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.