Best Testsigma code snippet using com.testsigma.util.HttpClient.execute
Source:RestAPIUtil.java  
...72            httpPost.setHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, "application/json; " + StandardCharsets.UTF_8);73            httpPost.setHeader(HttpHeaders.ACCEPT, "application/json; " + StandardCharsets.UTF_8);74            HttpEntity stringEntity = new StringEntity(jsonData.toString(), ContentType.APPLICATION_JSON);75            httpPost.setEntity(stringEntity);76            CloseableHttpResponse response = httpclient.execute(httpPost);77            dataObject = (JsonObject) getDataFromResponse(response, false);78        } finally {79            if (httpclient != null) httpclient.close();80        }81        listener.getLogger().println("Execution started:" + dataObject.toString());82        return dataObject.get("id").toString();83    }84    private String getExecutionAPI() {85      return String.format("%s%s",apiEndPoint,properties.getProperty("testsigma.execution.trigger.restapi"));86    }87    public boolean runExecutionStatusCheck(BuildListener listener, Secret apiKey, String runId, int maxWaitTimeInMinutes, int pollIntervalInMins)88            throws IOException, InterruptedException {89        // Safe check, if max build wait time is less than pre-defined poll interval90        pollIntervalInMins = (maxWaitTimeInMinutes < pollIntervalInMins) ? maxWaitTimeInMinutes : pollIntervalInMins;91        PrintStream consoleOut = listener.getLogger();92        String statusURL = String.format("%s/%s",getExecutionAPI(), runId);93        JsonObject responseObj;94        int noOfPolls = maxWaitTimeInMinutes / pollIntervalInMins;95        for (int i = 1; i <= noOfPolls; i++) {96            responseObj = (JsonObject) getTestPlanExecutionStatus(statusURL, apiKey.getPlainText().trim());97            String status = responseObj.get("status").toString();98            consoleOut.println("Test execution Status..." + status);99            if (status.trim().contains("STATUS_IN_PROGRESS")) {100                try {101                    Thread.sleep(pollIntervalInMins * 1000 * 60L);102                    consoleOut.println("Total time waited so far(in minutes)::" + ((i) * pollIntervalInMins));103                } catch (InterruptedException e) {104                    consoleOut.println("Thread interrupted by Jenkins..");105                    throw e;106                }107            } else {108                consoleOut.println("Test suites Execution completed");109                return true;110            }111        }112        return false;113    }114    private Object getTestPlanExecutionStatus(String statusURL, String apiKey) throws IOException {115        CloseableHttpClient httpclient = null;116        Object responseObj;117        try {118            httpclient = HttpClients.createDefault();119            HttpGet httpGet = new HttpGet(statusURL);120            httpGet.setHeader(org.apache.http.HttpHeaders.AUTHORIZATION, "Bearer " + apiKey.trim());121            httpGet.setHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, "application/json; " + StandardCharsets.UTF_8);122            httpGet.setHeader(HttpHeaders.ACCEPT, "application/json; " + StandardCharsets.UTF_8);123            CloseableHttpResponse response = httpclient.execute(httpGet);124            responseObj = getDataFromResponse(response, false);125        } finally {126            if (httpclient != null) httpclient.close();127        }128        return responseObj;129    }130    public String getReportsFilePath(BuildListener listener, String reportsFolder, Long buildID,131                                     String reportFileName) {132        String tempDir = System.getProperty("java.io.tmpdir");133        if (!isNullOrEmpty(reportsFolder)) {134            File givenDir = new File(reportsFolder);135            if (givenDir.exists() && givenDir.isDirectory()) {136                return String.format("%s%s%s%s%s", reportsFolder, File.separator, buildID, File.separator, reportFileName);137            }138        }139        listener.getLogger().println("System Temp dir:" + tempDir);140        return String.format("%s%s%s%s%s", tempDir, File.separator, buildID, File.separator, reportFileName);141    }142    public void saveTestReports(Secret apiKey, String runId, String reportsFilePath) throws IOException {143        CloseableHttpClient httpclient = null;144        Object responseObj = null;145        String reportsAPI = String.format("%s/%s",getReportsAPI(), runId);146        try {147            httpclient = HttpClients.createDefault();148            HttpGet httpGet = new HttpGet(reportsAPI);149            httpGet.setHeader(org.apache.http.HttpHeaders.AUTHORIZATION, "Bearer " + apiKey.getPlainText().trim());150            httpGet.setHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, "application/json; " + StandardCharsets.UTF_8);151            httpGet.setHeader(HttpHeaders.ACCEPT, "application/xml; " + StandardCharsets.UTF_8);152            CloseableHttpResponse response = httpclient.execute(httpGet);153            responseObj = getDataFromResponse(response, true);154            File reportsFile = new File(reportsFilePath);155            FileUtils.writeStringToFile(reportsFile, responseObj.toString());156            listener.getLogger().println("Reports saved to:"+reportsFile.getAbsolutePath());157        }catch(Exception e){158            listener.getLogger().println("Report generation failed..");159            listener.getLogger().println(ExceptionUtils.getStackTrace(e));160        }161        finally {162            if (httpclient != null) httpclient.close();163        }164    }165    private String getReportsAPI() {166        return String.format("%s%s", apiEndPoint,properties.getProperty("testsigma.reports.junit.restapi"));...Source:EnvironmentRunner.java  
...89      setRunnerEnvironmentRunResult(environmentRunResult);90      setRunnerExecutionId(testPlanId);91      beforeExecute();92      setStartedStatus();93      execute();94      afterExecute();95      setEnvironmentResult();96      setStoppedStatus();97    } catch (TestsigmaNoParallelRunException e){98      environmentRunResult.setResult(ResultConstant.STOPPED);99      environmentRunResult.setErrorCode(e.getErrorCode());100      environmentRunResult.setMessage(e.getMessage());101    } catch (AutomatorException e) {102      environmentRunResult.setResult(ResultConstant.NOT_EXECUTED);103      environmentRunResult.setErrorCode(e.getErrorCode());104      environmentRunResult.setMessage(e.getDispMessage());105      log.info("Test Engine Exception in TestSuiteDriver - " + environmentRunResult.getMessage() + " - " + environmentRunResult.getErrorCode());106      log.error(e.getMessage(), e);107    } finally {108      deleteFolder();109    }110    return environmentRunResult;111  }112  private void populateThreadContextData() {113    ThreadContext.put("TEST_DEVICE_RESULT", environmentRunResult.getId() + "");114    ThreadContext.put("TEST_PLAN", testDeviceEntity.getTestPlanId() + "");115    ThreadContext.put("TEST_PLAN_RESULT", testDeviceEntity.getExecutionRunId() + "");116  }117  protected void setEnvironmentResult() {118    if (!isRunning()) {119      environmentRunResult.setResult(ResultConstant.STOPPED);120      environmentRunResult.setMessage(AutomatorMessages.MSG_USER_ABORTED_EXECUTION);121      environmentRunResult.setErrorCode(com.testsigma.automator.constants.ErrorCodes.USER_STOPPED_EXECUTION);122    } else {123      environmentRunResult.setMessage(AutomatorMessages.MSG_ENVIRONMENT_SUCCESS);124    }125  }126  protected void afterExecute() throws AutomatorException {127  }128  private Platform getOs() {129    return (testDeviceEntity.getEnvSettings().getPlatform() != null) ?130      testDeviceEntity.getEnvSettings().getPlatform() : null;131  }132  public void deleteFolder() {133    TestDeviceSettings envSettings = EnvironmentRunner.getRunnerEnvironmentEntity().getEnvSettings();134    try {135      String fullPath = Paths.get(PathUtil.getInstance().getUploadPath(), envSettings.getEnvRunId() + "")136        .toFile().getAbsolutePath();137      File file = new File(fullPath);138      if (file.exists()) {139        FileUtils.deleteDirectory(file);140      } else {141        log.info("Directory doesn't exist. Unable to delete - " + file.getAbsolutePath());142      }143    } catch (IOException e) {144      log.error(e.getMessage(), e);145    }146  }147  protected abstract void execute() throws AutomatorException;148  protected String getTestPlanId() {149    return String.format("%s-%s", environmentRunResult.getId(), testDeviceEntity.getId());150  }151  protected abstract void checkForEmptyEnvironment() throws AutomatorException;152}...Source:FindAllBrokenImagesInPage.java  
...21public class FindAllBrokenImagesInPage extends WebAction {22    @TestData(reference = "url")23    private com.testsigma.sdk.TestData URL;24    @Override25    public com.testsigma.sdk.Result execute() throws NoSuchElementException {26        try {27            driver.get(URL.getValue().toString());28            driver.manage().window().maximize();29            List<String> brokenImages = new ArrayList<>();30            List<WebElement> image_list = new ArrayList<>();31            try {32                image_list = driver.findElements(By.tagName("img"));33                for (WebElement img : image_list) {34                    if (img != null) {35                        HttpClient client = HttpClientBuilder.create().build();36                        String src = img.getAttribute("src");37                        try {38                            if (src != null) {39                                HttpGet request = new HttpGet(src);40                                HttpResponse response = client.execute(request);41                                if (response.getStatusLine().getStatusCode() != 200) {42                                    System.out.println(img.getAttribute("outerHTML") + " has broken image.");43                                    brokenImages.add(img.getAttribute("src"));44                                }45                            }46                        } catch (Exception e) {47                            e.printStackTrace();48                            log(e.getMessage());49                        }50                    }51                }52            } catch (Exception e) {53                e.printStackTrace();54                log(e.getMessage());...execute
Using AI Code Generation
1package com.testsigma.util;2import java.io.IOException;3import java.util.ArrayList;4import java.util.HashMap;5import java.util.List;6import java.util.Map;7import org.apache.http.Header;8import org.apache.http.HttpEntity;9import org.apache.http.HttpResponse;10import org.apache.http.NameValuePair;11import org.apache.http.client.ClientProtocolException;12import org.apache.http.client.entity.UrlEncodedFormEntity;13import org.apache.http.client.methods.HttpGet;14import org.apache.http.client.methods.HttpPost;15import org.apache.http.client.methods.HttpUriRequest;16import org.apache.http.entity.StringEntity;17import org.apache.http.message.BasicNameValuePair;18import org.apache.http.util.EntityUtils;19public class HttpClient {20    private static final String CONTENT_TYPE = "Content-Type";21    private static final String APPLICATION_JSON = "application/json";22    private static final String APPLICATION_XML = "application/xml";23    private static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded";24    private static final String UTF_8 = "UTF-8";25    private static final String ACCEPT = "Accept";26    private static final String USER_AGENT = "User-Agent";27    private static final String USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0";28    public static HttpResponse executeGet(String url, Map<String, String> headers) throws ClientProtocolException, IOException {29        HttpGet httpGet = new HttpGet(url);30        return executeRequest(httpGet, headers);31    }32    public static HttpResponse executePost(String url, Map<String, String> headers, String body) throws ClientProtocolException, IOException {33        HttpPost httpPost = new HttpPost(url);34        if (body != null) {35            StringEntity entity = new StringEntity(body);36            httpPost.setEntity(entity);37        }38        return executeRequest(httpPost, headers);39    }execute
Using AI Code Generation
1import com.testsigma.util.HttpClient;2import com.testsigma.util.HttpResponse;3import java.net.URL;4import java.util.HashMap;5import java.util.Map;6public class TestHttp {7    public static void main(String[] args) throws Exception {8        HttpClient client = new HttpClient();9        Map<String, String> headers = new HashMap<String, String>();10        headers.put("Content-Type", "application/json");11        HttpResponse response = client.execute(url, "GET", headers, null);12        System.out.println(response);13    }14}15import java.io.BufferedReader;16import java.io.IOException;17import java.io.InputStream;18import java.io.InputStreamReader;19import java.net.HttpURLConnection;20import java.net.URL;21import java.util.Map;22public class HttpClient {23    public HttpResponse execute(URL url, String method, Map<String, String> headers, String body) throws IOException {24        HttpURLConnection connection = (HttpURLConnection) url.openConnection();25        connection.setRequestMethod(method);26        if (headers != null) {27            for (Map.Entry<String, String> entry : headers.entrySet()) {28                connection.setRequestProperty(entry.getKey(), entry.getValue());29            }30        }31        if (body != null) {32            connection.setDoOutput(true);33            connection.getOutputStream().write(body.getBytes());34        }35        int responseCode = connection.getResponseCode();36        String responseMessage = connection.getResponseMessage();37        String responseBody = null;38        if (responseCode == 200) {39            responseBody = readResponseBody(connection.getInputStream());40        } else {41            responseBody = readResponseBody(connection.getErrorStream());42        }43        return new HttpResponse(responseCode, responseMessage, responseBody);44    }45    private String readResponseBody(InputStream inputStream) throws IOException {46        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));47        StringBuffer buffer = new StringBuffer();48        String line = null;49        while ((line = reader.readLine()) != null) {50            buffer.append(line);51        }52        return buffer.toString();53    }54}55import java.util.HashMap;56import java.util.Map;57public class HttpResponse {58    private int responseCode;59    private String responseMessage;60    private String responseBody;61    public HttpResponse(int responseCode, String responseMessage, String responseBody) {62        this.responseCode = responseCode;63        this.responseMessage = responseMessage;64        this.responseBody = responseBody;65    }66    public int getResponseCode() {67        return responseCode;68    }execute
Using AI Code Generation
1import com.testsigma.util.HttpClient;2public class 2 {3public static void main(String[] args) throws Exception {4HttpClient client = new HttpClient();5System.out.println(response.getResponseBody());6}7}8import com.testsigma.util.HttpClient;9public class 3 {10public static void main(String[] args) throws Exception {11HttpClient client = new HttpClient();12System.out.println(response.getResponseBody());13}14}15import com.testsigma.util.HttpClient;16public class 4 {17public static void main(String[] args) throws Exception {18HttpClient client = new HttpClient();19System.out.println(response.getResponseBody());20}21}22import com.testsigma.util.HttpClient;23public class 5 {24public static void main(String[] args) throws Exception {25HttpClient client = new HttpClient();26System.out.println(response.getResponseBody());27}28}29import com.testsigma.util.HttpClient;30public class 6 {31public static void main(String[] args) throws Exception {32HttpClient client = new HttpClient();33System.out.println(response.getResponseBody());34}35}execute
Using AI Code Generation
1package com.testsigma.util;2import java.io.IOException;3import java.util.HashMap;4import java.util.Map;5import org.apache.http.HttpEntity;6import org.apache.http.HttpResponse;7import org.apache.http.ParseException;8import org.apache.http.client.ClientProtocolException;9import org.apache.http.client.methods.HttpPost;10import org.apache.http.entity.StringEntity;11import org.apache.http.impl.client.CloseableHttpClient;12import org.apache.http.impl.client.HttpClients;13import org.apache.http.util.EntityUtils;14public class HttpClient {15public static String execute(String url, Map<String, String> headers,16Map<String, String> params) throws ClientProtocolException, IOException {17CloseableHttpClient client = HttpClients.createDefault();18HttpPost post = new HttpPost(url);19StringEntity entity = new StringEntity(params.get("requestBody"));20post.setEntity(entity);21for (Map.Entry<String, String> header : headers.entrySet()) {22post.setHeader(header.getKey(), header.getValue());23}24HttpResponse response = client.execute(post);25HttpEntity responseEntity = response.getEntity();26String responseString = EntityUtils.toString(responseEntity);27return responseString;28}29}30package com.testsigma.util;31import java.io.IOException;32import java.util.HashMap;33import java.util.Map;34import org.apache.http.HttpEntity;35import org.apache.http.HttpResponse;36import org.apache.http.ParseException;37import org.apache.http.client.ClientProtocolException;38import org.apache.http.client.methods.HttpPost;39import org.apache.http.entity.StringEntity;40import org.apache.http.impl.client.CloseableHttpClient;41import org.apache.http.impl.client.HttpClients;42import org.apache.http.util.EntityUtils;43public class HttpClient {44public static String execute(String url, Map<String, String> headers,execute
Using AI Code Generation
1package com.testsigma.util;2import java.io.IOException;3import java.util.HashMap;4import java.util.Map;5import org.apache.http.HttpEntity;6import org.apache.http.HttpResponse;7import org.apache.http.client.ClientProtocolException;8import org.apache.http.client.methods.HttpUriRequest;9import org.apache.http.util.EntityUtils;10public class HttpClient {11    private static final String USER_AGENT = "Mozilla/5.0";12    public static void main(String[] args) throws ClientProtocolException, IOException {13        Map<String, String> headers = new HashMap<String, String>();14        headers.put("Content-Type", "application/json");15        headers.put("Connection", "keep-alive");16        headers.put("Accept", "application/json");17        headers.put("User-Agent", USER_AGENT);18        HttpUriRequest request = RequestBuilder.createGetRequest(url, headers);19        HttpResponse response = execute(request);20        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());21        HttpEntity entity = response.getEntity();22        String responseString = EntityUtils.toString(entity, "UTF-8");23        System.out.println("Response : " + responseString);24    }25    public static HttpResponse execute(HttpUriRequest request) throws ClientProtocolException, IOException {26        org.apache.http.client.HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();27        return client.execute(request);28    }29}30package com.testsigma.util;31import java.io.IOException;32import java.io.UnsupportedEncodingException;33import java.net.URI;34import java.net.URISyntaxException;35import java.net.URLEncoder;36import java.util.HashMap;37import java.util.Map;38import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;39public class RequestBuilder {40    public static HttpUriRequest createGetRequest(String url, Map<String, String> headers) throws URISyntaxException {41        HttpUriRequest request = new HttpGetWithEntity(url);42        for (String key : headers.keySet()) {43            request.setHeader(key, headers.get(key));44        }45        return request;46    }47    public static HttpUriRequest createPostRequest(String url, Map<String, String> headers, String body) throws URISyntaxException {48        HttpUriRequest request = new HttpPostWithEntity(url);49        for (String key : headers.keySet()) {50            request.setHeader(key, headers.get(key));51        }52        ((HttpPostWithEntity) request).setEntity(body);53        return request;Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
