Add header to all requests

Viewed 714

Is there any way to add an header to all requests?

I have to add an header to all requests. In production environments the header is added by a proxy.

Adding this header manually in all tests is annoying.

3 Answers

Are you using FeignClient for your requests?

If you are, and if your tests define a profile named test, you can use something like this:

@Configuration
public class FeignRequestConfiguration {

    @Bean
    @Profile("test")
    public RequestInterceptor feignRequestInterceptorTest() {
        return (RequestTemplate requestTemplate) -> {
            requestTemplate.header("Some-Header", "Some-Value");
        };
    }
}

As @pvpkiran suggested I've created the Filter

public class AddHeadersFilter implements Filter {

    @Override
    public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
        requestSpec.header(new Header(IntegrationBaseTest.HEADER_USER_NAME, "test-user"));

        return ctx.next(requestSpec, responseSpec);
    }

}

Then I've added it to all tests

    @BeforeClass
    public static void configureRestAssured() {
        RestAssured.filters(new AddHeadersFilter());
    }

Seems to work.

I've also added (I hope) helpful configuration

        HeaderConfig headerConfig = headerConfig()
                .overwriteHeadersWithName(HEADER_USER_NAME);
        RestAssured.config().headerConfig(headerConfig);

So there is a way to override the header in some tests

Use the below code . Using RequestSpecBuilder you can achieve this .

RequestSpecBuilder reqbuild=new RequestSpecBuilder();
        //Adding values like path parameters
        reqbuild.addPathParam("customers", "12212");
        reqbuild.addHeader("Content-Type", "application/json");
        requestSpecfication=reqbuild.build();

    given().spec(requestSpecfication).when().get("{customers}/").then().spec(responseSpecification).log().all();
Related