Best Cerberus-source code snippet using org.cerberus.service.rest.impl.RestService.executeHTTPCall
Source:RestService.java
...97 private static final boolean DEFAULT_PROXYAUTHENT_ACTIVATE = false;98 private static final String DEFAULT_PROXYAUTHENT_USER = "squid";99 private static final String DEFAULT_PROXYAUTHENT_PASSWORD = "squid";100 private static final Logger LOG = LogManager.getLogger(RestService.class);101 private AppService executeHTTPCall(CloseableHttpClient httpclient, HttpRequestBase httpget) throws Exception {102 try {103 // Create a custom response handler104 ResponseHandler<AppService> responseHandler = new ResponseHandler<AppService>() {105 @Override106 public AppService handleResponse(final HttpResponse response)107 throws ClientProtocolException, IOException {108 AppService myResponse = factoryAppService.create("", AppService.TYPE_REST,109 AppService.METHOD_HTTPGET, "", "", "", "", "", "", "", "", null, "", null);110 int responseCode = response.getStatusLine().getStatusCode();111 myResponse.setResponseHTTPCode(responseCode);112 myResponse.setResponseHTTPVersion(response.getProtocolVersion().toString());113 LOG.info(String.valueOf(responseCode) + " " + response.getProtocolVersion().toString());114 Header[] allHeaderList = response.getAllHeaders();115 for (Header header : allHeaderList) {116 myResponse.addResponseHeaderList(factoryAppServiceHeader.create(null, header.getName(),117 header.getValue(), "Y", 0, "", "", null, "", null));118 }119 HttpEntity entity = response.getEntity();120 myResponse.setResponseHTTPBody(entity != null ? EntityUtils.toString(entity) : null);121 return myResponse;122 }123 };124 return httpclient.execute(httpget, responseHandler);125 } catch (Exception ex) {126 LOG.error(ex.toString());127 throw ex;128 } finally {129 httpclient.close();130 }131 }132 @Override133 public AnswerItem<AppService> callREST(String servicePath, String requestString, String method,134 List<AppServiceHeader> headerList, List<AppServiceContent> contentList, String token, int timeOutMs,135 String system) {136 AnswerItem result = new AnswerItem();137 AppService serviceREST = factoryAppService.create("", AppService.TYPE_REST, method, "", "", "", "", "", "", "",138 "", null, "", null);139 serviceREST.setProxy(false);140 serviceREST.setProxyHost(null);141 serviceREST.setProxyPort(0);142 serviceREST.setProxyWithCredential(false);143 serviceREST.setProxyUser(null);144 serviceREST.setTimeoutms(timeOutMs);145 MessageEvent message = null;146 if (StringUtil.isNullOrEmpty(servicePath)) {147 message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_SERVICEPATHMISSING);148 result.setResultMessage(message);149 return result;150 }151 if (StringUtil.isNullOrEmpty(method)) {152 message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_METHODMISSING);153 result.setResultMessage(message);154 return result;155 }156 // If token is defined, we add 'cerberus-token' on the http header.157 if (token != null) {158 headerList159 .add(factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null));160 }161 CloseableHttpClient httpclient;162 if (proxyService.useProxy(servicePath, system)) {163 String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system,164 DEFAULT_PROXY_HOST);165 int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system,166 DEFAULT_PROXY_PORT);167 serviceREST.setProxy(true);168 serviceREST.setProxyHost(proxyHost);169 serviceREST.setProxyPort(proxyPort);170 HttpHost proxyHostObject = new HttpHost(proxyHost, proxyPort);171 if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system,172 DEFAULT_PROXYAUTHENT_ACTIVATE)) {173 String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user",174 system, DEFAULT_PROXYAUTHENT_USER);175 String proxyPassword = parameterService.getParameterStringByKey(176 "cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);177 serviceREST.setProxyWithCredential(true);178 serviceREST.setProxyUser(proxyUser);179 CredentialsProvider credsProvider = new BasicCredentialsProvider();180 credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),181 new UsernamePasswordCredentials(proxyUser, proxyPassword));182 LOG.debug("Activating Proxy With Authentification.");183 httpclient = HttpClientBuilder.create().setProxy(proxyHostObject)184 .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())185 .setDefaultCredentialsProvider(credsProvider).build();186 } else {187 LOG.debug("Activating Proxy (No Authentification).");188 httpclient = HttpClientBuilder.create().setProxy(proxyHostObject).build();189 }190 } else {191 httpclient = HttpClients.createDefault();192 }193 try {194 RequestConfig requestConfig;195 // Timeout setup.196 requestConfig = RequestConfig.custom().setConnectTimeout(timeOutMs).setConnectionRequestTimeout(timeOutMs)197 .setSocketTimeout(timeOutMs).build();198 AppService responseHttp = null;199 switch (method) {200 case AppService.METHOD_HTTPGET:201 LOG.info("Start preparing the REST Call (GET). " + servicePath + " - " + requestString);202 servicePath = StringUtil.addQueryString(servicePath, requestString);203 serviceREST.setServicePath(servicePath);204 HttpGet httpGet = new HttpGet(servicePath);205 // Timeout setup.206 httpGet.setConfig(requestConfig);207 // Header.208 for (AppServiceHeader contentHeader : headerList) {209 httpGet.addHeader(contentHeader.getKey(), contentHeader.getValue());210 }211 serviceREST.setHeaderList(headerList);212 // Saving the service before the call Just in case it goes wrong (ex : timeout).213 result.setItem(serviceREST);214 LOG.info("Executing request " + httpGet.getRequestLine());215 responseHttp = executeHTTPCall(httpclient, httpGet);216 if (responseHttp != null) {217 serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());218 serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());219 serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());220 serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());221 }222 break;223 case AppService.METHOD_HTTPPOST:224 LOG.info("Start preparing the REST Call (POST). " + servicePath);225 serviceREST.setServicePath(servicePath);226 HttpPost httpPost = new HttpPost(servicePath);227 // Timeout setup.228 httpPost.setConfig(requestConfig);229 // Content230 if (!(StringUtil.isNullOrEmpty(requestString))) {231 // If requestString is defined, we POST it.232 InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));233 InputStreamEntity reqEntity = new InputStreamEntity(stream);234 reqEntity.setChunked(true);235 httpPost.setEntity(reqEntity);236 serviceREST.setServiceRequest(requestString);237 } else {238 // If requestString is not defined, we POST the list of key/value request.239 List<NameValuePair> nvps = new ArrayList<NameValuePair>();240 for (AppServiceContent contentVal : contentList) {241 nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));242 }243 httpPost.setEntity(new UrlEncodedFormEntity(nvps));244 serviceREST.setContentList(contentList);245 }246 // Header.247 for (AppServiceHeader contentHeader : headerList) {248 httpPost.addHeader(contentHeader.getKey(), contentHeader.getValue());249 }250 serviceREST.setHeaderList(headerList);251 // Saving the service before the call Just in case it goes wrong (ex : timeout).252 result.setItem(serviceREST);253 LOG.info("Executing request " + httpPost.getRequestLine());254 responseHttp = executeHTTPCall(httpclient, httpPost);255 if (responseHttp != null) {256 serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());257 serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());258 serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());259 serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());260 } else {261 message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);262 message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));263 message.setDescription(message.getDescription().replace("%DESCRIPTION%",264 "Any issue was found when calling the service. Coud be a reached timeout during the call (."265 + timeOutMs + ")"));266 result.setResultMessage(message);267 return result;268 }269 break;270 case AppService.METHOD_HTTPDELETE:271 LOG.info("Start preparing the REST Call (DELETE). " + servicePath);272 servicePath = StringUtil.addQueryString(servicePath, requestString);273 serviceREST.setServicePath(servicePath);274 HttpDelete httpDelete = new HttpDelete(servicePath);275 // Timeout setup.276 httpDelete.setConfig(requestConfig);277 // Header.278 for (AppServiceHeader contentHeader : headerList) {279 httpDelete.addHeader(contentHeader.getKey(), contentHeader.getValue());280 }281 serviceREST.setHeaderList(headerList);282 // Saving the service before the call Just in case it goes wrong (ex : timeout).283 result.setItem(serviceREST);284 LOG.info("Executing request " + httpDelete.getRequestLine());285 responseHttp = executeHTTPCall(httpclient, httpDelete);286 if (responseHttp != null) {287 serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());288 serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());289 serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());290 serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());291 }292 break;293 case AppService.METHOD_HTTPPUT:294 LOG.info("Start preparing the REST Call (PUT). " + servicePath);295 serviceREST.setServicePath(servicePath);296 HttpPut httpPut = new HttpPut(servicePath);297 // Timeout setup.298 httpPut.setConfig(requestConfig);299 // Content300 if (!(StringUtil.isNullOrEmpty(requestString))) {301 // If requestString is defined, we POST it.302 InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));303 InputStreamEntity reqEntity = new InputStreamEntity(stream);304 reqEntity.setChunked(true);305 httpPut.setEntity(reqEntity);306 serviceREST.setServiceRequest(requestString);307 } else {308 // If requestString is not defined, we PUT the list of key/value request.309 List<NameValuePair> nvps = new ArrayList<NameValuePair>();310 for (AppServiceContent contentVal : contentList) {311 nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));312 }313 httpPut.setEntity(new UrlEncodedFormEntity(nvps));314 serviceREST.setContentList(contentList);315 }316 // Header.317 for (AppServiceHeader contentHeader : headerList) {318 httpPut.addHeader(contentHeader.getKey(), contentHeader.getValue());319 }320 serviceREST.setHeaderList(headerList);321 // Saving the service before the call Just in case it goes wrong (ex : timeout).322 result.setItem(serviceREST);323 LOG.info("Executing request " + httpPut.getRequestLine());324 responseHttp = executeHTTPCall(httpclient, httpPut);325 if (responseHttp != null) {326 serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());327 serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());328 serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());329 serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());330 } else {331 message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);332 message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));333 message.setDescription(message.getDescription().replace("%DESCRIPTION%",334 "Any issue was found when calling the service. Coud be a reached timeout during the call (."335 + timeOutMs + ")"));336 result.setResultMessage(message);337 return result;338 }339 break;340 case AppService.METHOD_HTTPPATCH:341 LOG.info("Start preparing the REST Call (PUT). " + servicePath);342 serviceREST.setServicePath(servicePath);343 HttpPatch httpPatch = new HttpPatch(servicePath);344 // Timeout setup.345 httpPatch.setConfig(requestConfig);346 // Content347 if (!(StringUtil.isNullOrEmpty(requestString))) {348 // If requestString is defined, we POST it.349 InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));350 InputStreamEntity reqEntity = new InputStreamEntity(stream);351 reqEntity.setChunked(true);352 httpPatch.setEntity(reqEntity);353 serviceREST.setServiceRequest(requestString);354 } else {355 // If requestString is not defined, we PUT the list of key/value request.356 List<NameValuePair> nvps = new ArrayList<NameValuePair>();357 for (AppServiceContent contentVal : contentList) {358 nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));359 }360 httpPatch.setEntity(new UrlEncodedFormEntity(nvps));361 serviceREST.setContentList(contentList);362 }363 // Header.364 for (AppServiceHeader contentHeader : headerList) {365 httpPatch.addHeader(contentHeader.getKey(), contentHeader.getValue());366 }367 serviceREST.setHeaderList(headerList);368 // Saving the service before the call Just in case it goes wrong (ex : timeout).369 result.setItem(serviceREST);370 LOG.info("Executing request " + httpPatch.getRequestLine());371 responseHttp = executeHTTPCall(httpclient, httpPatch);372 if (responseHttp != null) {373 serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());374 serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());375 serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());376 serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());377 } else {378 message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);379 message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));380 message.setDescription(message.getDescription().replace("%DESCRIPTION%",381 "Any issue was found when calling the service. Coud be a reached timeout during the call (."382 + timeOutMs + ")"));383 result.setResultMessage(message);384 return result;385 }...
executeHTTPCall
Using AI Code Generation
1String method = "GET";2String header = "";3String body = "";4String contentType = "";5String response = org.cerberus.service.rest.impl.RestService.executeHTTPCall(url, method, header, body, contentType);6System.out.println(response);7exitTestCase();8exitTest();9exitTestData();10exitTestBattery();11exitBatch();12exitExecution();
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!!