Sending HTTP requests and parsing JSON in TestComplete
Tasks
Sending HTTP requests and parsing JSON in TestComplete. Here are the steps how it can be resolved:
- Send a GET request to https://dog.ceo/api/breeds/image/random. Check the status of the request - if it is successful, the response will return a JSON that contains a link to a random picture of a dog.
- Parse the returned JSON to extract the link to the image. JavaScript and Python provide support for JSON out of the box; for other languages, you might want to parse JSON as a string or use regular expressions.
- Send a GET request to the URL obtained from the previous response - this will return an image.
4. Save the response as an image to a JPG file by calling the SaveToFile method like this: response.SaveToFile("C:\\image.jpg")
Solution
//JavaScript
function getThisDog(https) {
var aqHttpRequest = aqHttp.CreateGetRequest(https);
aqHttpRequest.SetHeader("Accept", "application/vnd.api+json; version=1");
aqHttpRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
aqHttpRequest.SetHeader("Accept-Language", "pl");
aqHttpRequest.SetHeader("Accept-Charset", "utf-8, iso-8859-13;q=0.8");
aqHttpRequest.SetHeader("Content-Language", "pl");
var aqHttpRes = aqHttpRequest.Send();
Log.Message(aqHttpRes.Text);
return aqHttpRes;
}
function parseThisDog() {
let jsonResponse = getThisDog("https://dog.ceo/api/breeds/image/random");
if(jsonResponse.StatusCode === 200) {
let doggyJson = JSON.parse(jsonResponse.Text);
let dogImage = getThisDog(doggyJson.message);
let randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
dogImage.SaveToFile("C:\\TEST-TRASH\\" + randomString + "dog.jpg");
} else {
Log.Error("Something went wrong while trying to connect")
}
}
Screen of img:
Published 4 years ago
Version 1.0