benni
July 10, 2019, 8:28am
1
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("https://api.............com/auth");
RequestSpecification request = RestAssured.given();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
request.headers("Accept", "application/json");
request.headers("Authorization", prop.getProperty("token"));
conn.setRequestMethod("GET");
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!!
Thanks!
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 https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html for more details.
benni
July 11, 2019, 9:39am
3
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()
.url("https://api....../auth")
.header("Authorization", "apiToken")
.post(body)
.build();
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();
System.out.println(response);
}