Sending HTTP headers

Course Home | Code Example

For this lesson we are going to look at how to add HTTP headers to a request and see how they affect the response we get back.

Adding a header to a request

Start off by creating a new test and adding in the following code and running it:

Header acceptHeader = new Header("accept","text/plain");

Response response = given()
                        .header(acceptHeader)
                        .get("https://restful-booker.herokuapp.com/booking/1");

int statusCode = response.getStatusCode();

assertThat(statusCode, is(200));

Hang on! When it runs it fails!!! Whats up with that???

What we have done is called another method before get(), specifically the header() method which will add an HTTP header to your request before it’s sent. The header we passed to the request was create before hand by using the Rest-Assured Header object where we added the name of the header (accept) and the value (text/plain).

And this is what is causing the test to fail. We have set the wrong value for the header. So let’s update the acceptHeader line to the correct value and then run the test again:

Header acceptHeader = new Header("accept","application/json");

Hey presto, the test passes!

Next Lesson ➔

Mark Winteringham's photo
Author

Mark Winteringham

@2bittester

Mark Winteringham is a tester, toolsmith and the Ministry of Testing DojoBoss with over 10 years experience providing testing expertise on award-winning projects across a wide range of technology sectors including BBC, Barclays, UK Government and Thomson Reuters. He is an advocate for modern risk-based testing practices and trains teams in Automation in Testing, Behaviour Driven Development and Exploratory testing techniques. He is also the co-founder of Software Testing Clinic a community raising awareness of careers in testing and improving testing education. You can find him on Twitter @2bittester.

Comments