Forum Discussion

sonya_m's avatar
sonya_m
SmartBear Alumni (Retired)
5 years ago

[TechCorner Challenge #10] Sending HTTP requests and parsing JSON in TestComplete

Hi everyone!   Let’s start September with a new challenge in the TestComplete Community! We are going to learn something great today. And, by completing the tasks, you will not only improve your ...
  • Wamboo's avatar
    5 years ago

    Task: Create a script in TestComplete that will get an image link from this API endpoint (https://dog.ceo/api/breeds/image/random) and save the image on the machine. Post your script and the image you got to the comments!

     

    This is a solution created for [TechCorner Challenge #10]

     

    Hi Sonya,

     

    I'd do it like this.

     

     

    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 in attach.