How to use setHeaders method of com.testsigma.automator.webservices.WebserviceUtil class

Best Testsigma code snippet using com.testsigma.automator.webservices.WebserviceUtil.setHeaders

Source:WebserviceUtil.java Github

copy

Full Screen

...70 ((Map<String, Object>) (testcaseStep.getAdditionalData().get(TestCaseStepEntity.REST_DETAILS_KEY))).put("url", entity.getUrl());71 resObj.setStatus(response.getStatusCode());72 if (entity.getStoreMetadata()) {73 resObj.setContent(response.getResponseText());74 resObj.setHeaders(response.getHeadersMap());75 }76 result.getMetadata().setRestResult(resObj);77 new RestApiResponseValidator(entity, result, response).validateResponse();78 new RestAPIRunTimeDataProcessor(entity,result).storeResponseData(response,envSettings);79 } catch (Exception e) {80 log.error("Error while executing Rest Step:"+testcaseStep, e);81 if (e instanceof AutomatorException) {82 result.setResult(ResultConstant.FAILURE);83 result.setMessage(e.getMessage());84 } else {85 String genericExceptionMessage = getExceptionSpecificMessage(e, result);86 result.setResult(ResultConstant.FAILURE);87 result.setMessage(genericExceptionMessage);88 }89 }90 result.getMetadata().setRestResult(resObj);91 log.debug("Test Step Result :: " + new ObjectMapperService().convertToJson(result));92 }93 private String getExceptionSpecificMessage(Exception exception, TestCaseStepResult testCaseStepResult) {94 String resultMessage;95 if(testCaseStepResult.getMessage() != null){//If specific Message is already set, we show the same in result96 return testCaseStepResult.getMessage();97 }98 if (exception instanceof PathNotFoundException) {99 resultMessage = AutomatorMessages.MSG_INVALID_PATH;100 } else if (exception instanceof ClientProtocolException) {101 if (exception.getCause() instanceof CircularRedirectException) {102 resultMessage = exception.getCause().getLocalizedMessage();103 } else {104 resultMessage = exception.getLocalizedMessage();105 }106 } else if (exception.getCause() instanceof ProtocolException) {107 resultMessage = AutomatorMessages.MSG_REST_INVALID_URL;108 } else if (exception instanceof UnknownHostException) {109 resultMessage = AutomatorMessages.MSG_INVALID_URL;110 } else {111 resultMessage = exception.getLocalizedMessage();112 }113 return resultMessage;114 }115 private Map<String, String> fetchHeadersFromRestStep(RestfulStepEntity restfulStepEntity) {116 Map<String, String> headers = new HashMap<>();117 if (StringUtils.isNotBlank(restfulStepEntity.getRequestHeaders())) {118 headers = new ObjectMapperService().parseJson(restfulStepEntity.getRequestHeaders(), new TypeReference<>() {119 });120 }121 return headers;122 }123 private void initializeHttpClient(RestfulStepEntity restfulStepEntity) {124 RequestConfig config = RequestConfig.custom()125 .setConnectTimeout(CONNECTION_TIMEOUT)126 .setSocketTimeout(SOCKET_TIMEOUT).build();127 if (restfulStepEntity.getFollowRedirects()) {128 httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();129 } else {130 httpclient = HttpClients.custom().setDefaultRequestConfig(config).disableRedirectHandling().build();131 }132 }133 private void setAuthorizationHeaders(RestfulStepEntity entity, Map<String, String> headers) {134 log.debug("Set Authorization headers for entity:" + entity);135 log.debug("Set Authorization headers ,headers:" + headers);136 if (entity.getAuthorizationType() != null) {137 headers = (headers != null) ? headers : new HashMap<>();138 Map<String, String> info = new ObjectMapperService().parseJson(entity.getAuthorizationValue(),139 new TypeReference<>() {140 });141 if (AuthorizationTypes.BASIC == entity.getAuthorizationType()) {142 headers.put(HttpHeaders.AUTHORIZATION,143 com.testsigma.automator.http.HttpClient.BASIC_AUTHORIZATION + " " +144 encodedCredentials(info.get("username") + ":" + info.get("password")));145 } else if (entity.getAuthorizationType() == AuthorizationTypes.BEARER) {146 headers.put("Authorization", "Bearer " + info.get("Bearertoken"));147 }148 }149 }150 private String encodedCredentials(String input) {151 String authHeader = "";152 try {153 byte[] encodedAuth = Base64.encodeBase64(input.getBytes(StandardCharsets.ISO_8859_1));154 if (encodedAuth != null) {155 authHeader = new String(encodedAuth);156 }157 } catch (Exception ignore) {158 }159 return authHeader;160 }161 private void setDefaultHeaders(RestfulStepEntity entity, Map<String, String> headers) {162 log.debug("Setting default headers for entity:" + entity);163 log.debug("Set default headers, headers:" + headers);164 try {165 headers = (headers != null) ? headers : new HashMap<String, String>();166 if (headers.get("Host") == null) {167 URL url = new URL(entity.getUrl());168 headers.put("Host", url.getHost());169 }170 if (headers.get("Content-Type") == null) {171 headers.put("Content-Type", "application/json");172 }173 } catch (Exception e) {174 log.error("error while setting default headers");175 }176 }177 private HttpEntity getEntity(RestfulStepEntity entity, Map<String, String> envSettings, Map<String, String> headers) throws Exception {178 MultipartEntityBuilder builder = MultipartEntityBuilder.create();179 if (entity.getIsMultipart() != null && entity.getIsMultipart()) {180 removeContentTypeHeader(headers);181 Map<String, Object> payload = new ObjectMapperService().parseJson(entity.getPayload(), new TypeReference<>() {182 });183 for (Map.Entry<String, Object> data : payload.entrySet()) {184 removeContentTypeHeader(headers);185 boolean isFileUrl = data.getValue() != null && (data.getValue().toString().startsWith("http")186 || data.getValue().toString().startsWith("https"));187 if (isFileUrl) {188 String filePath = downloadFile(data.getValue().toString(), envSettings);189 String[] fileNames = filePath.split(File.separator);190 builder.addBinaryBody(data.getKey(), new File(filePath), ContentType.DEFAULT_BINARY, fileNames[fileNames.length - 1]);191 } else {192 builder.addPart(data.getKey(), new StringBody(new ObjectMapperService().convertToJson(data.getValue()), ContentType.APPLICATION_JSON));193 }194 }195 return builder.build();196 } else if (entity.getPayload() != null) {197 return new StringEntity(entity.getPayload());198 }199 return null;200 }201 public void removeContentTypeHeader(Map<String, String> headers) {202 String contenttype = null;203 for (Map.Entry<String, String> entry : headers.entrySet()) {204 if (entry.getKey().equalsIgnoreCase("content-type")) {205 contenttype = entry.getKey();206 break;207 }208 }209 if (contenttype != null) {210 headers.remove(contenttype);211 }212 }213 public HttpResponse<String> executeRestCall(String url, RequestMethod method, Map<String, String> headers,214 HttpEntity input) throws IOException {215 HttpResponse<String> returnResponse;216 log.debug(String.format("Executing Rest API call with below props\n method::%s\n, headers::%s\n HttpEntity::%s", method,217 headers, input));218 try {219 HttpUriRequest request = null;220 switch (method) {221 case GET:222 request = new HttpGet(url);223 setHeaders(request, headers);224 break;225 case POST:226 request = new HttpPost(url);227 if (input != null)228 ((HttpPost) request).setEntity(input);229 setHeaders(request, headers);230 break;231 case PUT:232 request = new HttpPut(url);233 if (input != null)234 ((HttpPut) request).setEntity(input);235 setHeaders(request, headers);236 break;237 case PATCH:238 request = new HttpPatch(url);239 if (input != null)240 ((HttpPatch) request).setEntity(input);241 setHeaders(request, headers);242 break;243 case DELETE:244 request = new HttpDelete(url);245 setHeaders(request, headers);246 break;247 case OPTIONS:248 request = new HttpOptions(url);249 setHeaders(request, headers);250 break;251 case TRACE:252 request = new HttpTrace(url);253 setHeaders(request, headers);254 break;255 case HEAD:256 request = new HttpHead(url);257 setHeaders(request, headers);258 break;259 default:260 break;261 }262 log.debug("***Executing REST API Call***");263 org.apache.http.HttpResponse response = httpclient.execute(request);264 log.debug("URL : " + url);265 log.debug("Response Status Code : " + response.getStatusLine().getStatusCode());266 returnResponse = new HttpResponse<>(response, new TypeReference<>() {267 });268 return returnResponse;269 } catch (Exception e) {270 throw e;271 } finally {272 HttpClientUtils.closeQuietly(httpclient);273 }274 }275 private void setHeaders(HttpUriRequest request, Map<String, String> headers) {276 if (headers != null) {277 for (String key : headers.keySet()) {278 request.addHeader(key, headers.get(key));279 }280 }281 }282 private String downloadFile(String fileUrl, Map<String, String> envSettings) throws Exception {283 try {284 if (fileUrl.startsWith(HTTP) || fileUrl.startsWith(HTTPS)) {285 String fileName = FilenameUtils.getName(new java.net.URL(fileUrl).getPath());286 String filePath = getDownloadFilePath(envSettings);287 com.testsigma.automator.http.HttpClient httpClient = EnvironmentRunner.getAssetsHttpClient();288 HttpResponse<String> response = httpClient.downloadFile(fileUrl, filePath + File.separator + fileName);289 if (response != null && response.getStatusCode() == HttpStatus.OK.value()) {...

Full Screen

Full Screen

setHeaders

Using AI Code Generation

copy

Full Screen

1import com.testsigma.automator.webservices.WebserviceUtil;2Map<String, String> headers = new HashMap<String, String>();3headers.put("Content-Type", "application/json");4headers.put("Accept", "application/json");5WebserviceUtil.setHeaders(headers);6import com.testsigma.automator.webservices.WebserviceUtil;7Map<String, String> headers = new HashMap<String, String>();8headers.put("Content-Type", "application/json");9headers.put("Accept", "application/json");10WebserviceUtil.setHeaders(headers);11import com.testsigma.automator.webservices.WebserviceUtil;12Map<String, String> headers = new HashMap<String, String>();13headers.put("Content-Type", "application/json");14headers.put("Accept", "application/json");15WebserviceUtil.setHeaders(headers);16import com.testsigma.automator.webservices.WebserviceUtil;17Map<String, String> headers = new HashMap<String, String>();18headers.put("Content-Type", "application/json");19headers.put("Accept", "application/json");20WebserviceUtil.setHeaders(headers);

Full Screen

Full Screen

setHeaders

Using AI Code Generation

copy

Full Screen

1import com.testsigma.automator.webservices.WebserviceUtil;2import com.testsigma.automator.webservices.WebserviceUtil;3public class WebserviceUtilSetHeaders {4 public static void main(String[] args) {5 WebserviceUtil webserviceUtil = new WebserviceUtil();6 webserviceUtil.setHeaders("Content-Type", "application/json");7 webserviceUtil.setHeaders("Accept", "application/json");8 }9}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful