Send API request to login before running java test

Hi there,
I am wanting to call an API endpoint to login “behind the scenes”, before the simulator opens, so my tests don’t always take so long.
Does anyone know how to do this?
I currently am trying something along the lines of:

public void apiLogin() throws Exception {
    URL url = new URL("");
    RequestSpecification request = RestAssured.given();
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    request.headers("Accept", "application/json");
    request.headers("Authorization", prop.getProperty("token"));
    conn.setRequestProperty("email", "[email protected]" );
    conn.setRequestProperty("password", "TestPassword" );

    if (conn.getResponseCode() == 200) {
} else {
    throw new RuntimeException("HTTP error code : "
            + conn.getResponseCode() + " " + conn.getResponseMessage());


But this is not working.

Any help would be great!!

Selenium library uses OkHttp internally (which means it is already available for you as well). It is a pretty nicely designed one and easy to work with. Check for more details.

Thank you, @mykola-mokhnach.

I now have the code shown below, but i am getting an error for this line:
try (Response response = client.newCall(request).execute()).

Not sure how to fix this? I have updated everything possible, to my knowledge. The error I am seeing is:

Error:(20, 13) java: try-with-resources is not supported in -source 1.5
(use -source 7 or higher to enable try-with-resources)

public class apiCalls {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    String get() throws IOException {
        RequestBody body = RequestBody.create(JSON,
                "email : [email protected], password : TestPassword");
        Request request = new Request.Builder()
                .header("Authorization", "apiToken")
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
    public static void main(String[] args) throws IOException {
        apiCalls example = new apiCalls();
        String response = example.get();

Google is your friend:"use+-source+7+or+higher+to+enable+try-with-resources"

1 Like