How to use HttpUtils method of com.intuit.karate.http.HttpUtils class

Best Karate code snippet using com.intuit.karate.http.HttpUtils.HttpUtils

Source:FeatureBackend.java Github

copy

Full Screen

...35import com.intuit.karate.XmlUtils;36import com.intuit.karate.exception.KarateException;37import com.intuit.karate.http.HttpRequest;38import com.intuit.karate.http.HttpResponse;39import com.intuit.karate.http.HttpUtils;40import java.util.List;41import java.util.Map;42/**43 *44 * @author pthomas345 */46public class FeatureBackend {47 private final Feature feature;48 private final StepActions actions;49 private boolean corsEnabled;50 private final ScenarioContext context;51 private final String featureName;52 private static void putBinding(String name, ScenarioContext context) {53 String function = "function(a){ return " + ScriptBindings.KARATE + "." + name + "(a) }";54 context.vars.put(name, Script.evalJsExpression(function, context));55 }56 57 private static void putBinding2(String name, ScenarioContext context) {58 String function = "function(a, b){ return " + ScriptBindings.KARATE + "." + name + "(a, b) }";59 context.vars.put(name, Script.evalJsExpression(function, context));60 } 61 public boolean isCorsEnabled() {62 return corsEnabled;63 }64 public ScenarioContext getContext() {65 return context;66 }67 public FeatureBackend(Feature feature) {68 this(feature, null);69 }70 public FeatureBackend(Feature feature, Map<String, Object> arg) {71 this.feature = feature;72 featureName = feature.getPath().toFile().getName();73 CallContext callContext = new CallContext(null, false);74 FeatureContext featureContext = new FeatureContext(null, feature, null);75 actions = new StepActions(featureContext, callContext, null, null);76 context = actions.context;77 putBinding(ScriptBindings.PATH_MATCHES, context);78 putBinding(ScriptBindings.METHOD_IS, context);79 putBinding(ScriptBindings.PARAM_VALUE, context);80 putBinding(ScriptBindings.TYPE_CONTAINS, context);81 putBinding(ScriptBindings.ACCEPT_CONTAINS, context);82 putBinding2(ScriptBindings.HEADER_CONTAINS, context);83 putBinding(ScriptBindings.BODY_PATH, context);84 if (arg != null) {85 arg.forEach((k, v) -> context.vars.put(k, v));86 }87 // the background is evaluated one-time88 if (feature.isBackgroundPresent()) {89 for (Step step : feature.getBackground().getSteps()) {90 Result result = Engine.executeStep(step, actions);91 if (result.isFailed()) {92 String message = "server-side background init failed - " + featureName + ":" + step.getLine();93 context.logger.error(message);94 throw new KarateException(message, result.getError());95 }96 }97 }98 // this is a special case, we support the auto-handling of cors99 // only if '* configure cors = true' has been done in the Background100 corsEnabled = context.getConfig().isCorsEnabled(); 101 context.logger.info("backend initialized");102 }103 public ScriptValueMap handle(ScriptValueMap args) {104 boolean matched = false;105 context.vars.putAll(args);106 for (FeatureSection fs : feature.getSections()) {107 if (fs.isOutline()) {108 context.logger.warn("skipping scenario outline - {}:{}", featureName, fs.getScenarioOutline().getLine());109 break;110 }111 Scenario scenario = fs.getScenario();112 if (isMatchingScenario(scenario)) {113 matched = true;114 for (Step step : scenario.getSteps()) {115 Result result = Engine.executeStep(step, actions);116 if (result.isAborted()) {117 context.logger.debug("abort at {}:{}", featureName, step.getLine());118 break;119 }120 if (result.isFailed()) {121 String message = "server-side scenario failed - " + featureName + ":" + step.getLine();122 context.logger.error(message);123 throw new KarateException(message, result.getError());124 }125 }126 break; // process only first matching scenario127 }128 }129 if (!matched) {130 context.logger.warn("no scenarios matched");131 }132 return context.vars;133 }134 private boolean isMatchingScenario(Scenario scenario) {135 String expression = StringUtils.trimToNull(scenario.getName() + scenario.getDescription());136 if (expression == null) {137 context.logger.debug("scenario matched: (empty)");138 return true;139 }140 try {141 ScriptValue sv = Script.evalJsExpression(expression, context);142 if (sv.isBooleanTrue()) {143 context.logger.debug("scenario matched: {}", expression);144 return true;145 } else {146 context.logger.debug("scenario skipped: {}", expression);147 return false;148 }149 } catch (Exception e) {150 context.logger.warn("scenario match evaluation failed: {}", e.getMessage());151 return false;152 }153 }154 155 private static final String VAR_AFTER_SCENARIO = "afterScenario";156 private static final String ALLOWED_METHODS = "GET, HEAD, POST, PUT, DELETE, PATCH";157 158 public HttpResponse buildResponse(HttpRequest request, long startTime) {159 if (corsEnabled && "OPTIONS".equals(request.getMethod())) {160 HttpResponse response = new HttpResponse(startTime, System.currentTimeMillis());161 response.setStatus(200);162 response.addHeader(HttpUtils.HEADER_ALLOW, ALLOWED_METHODS);163 response.addHeader(HttpUtils.HEADER_AC_ALLOW_ORIGIN, "*");164 response.addHeader(HttpUtils.HEADER_AC_ALLOW_METHODS, ALLOWED_METHODS);165 List requestHeaders = request.getHeaders().get(HttpUtils.HEADER_AC_REQUEST_HEADERS);166 if (requestHeaders != null) {167 response.putHeader(HttpUtils.HEADER_AC_ALLOW_HEADERS, requestHeaders);168 } 169 return response;170 }171 Match match = new Match()172 .text(ScriptValueMap.VAR_REQUEST_URL_BASE, request.getUrlBase())173 .text(ScriptValueMap.VAR_REQUEST_URI, request.getUri())174 .text(ScriptValueMap.VAR_REQUEST_METHOD, request.getMethod())175 .def(ScriptValueMap.VAR_REQUEST_HEADERS, request.getHeaders())176 .def(ScriptValueMap.VAR_RESPONSE_STATUS, 200)177 .def(ScriptValueMap.VAR_REQUEST_PARAMS, request.getParams());178 byte[] requestBytes = request.getBody();179 if (requestBytes != null) {180 match.def(ScriptValueMap.VAR_REQUEST_BYTES, requestBytes);181 String requestString = FileUtils.toString(requestBytes);182 Object requestBody = requestString;183 if (Script.isJson(requestString)) {184 try {185 requestBody = JsonUtils.toJsonDoc(requestString);186 } catch (Exception e) {187 context.logger.warn("json parsing failed, request data type set to string: {}", e.getMessage());188 }189 } else if (Script.isXml(requestString)) {190 try {191 requestBody = XmlUtils.toXmlDoc(requestString);192 } catch (Exception e) {193 context.logger.warn("xml parsing failed, request data type set to string: {}", e.getMessage());194 }195 }196 match.def(ScriptValueMap.VAR_REQUEST, requestBody);197 }198 ScriptValue responseValue, responseStatusValue, responseHeaders, afterScenario;199 Map<String, Object> responseHeadersMap, configResponseHeadersMap;200 // this is a sledgehammer approach to concurrency !201 // which is why for simulating 'delay', users should use the VAR_AFTER_SCENARIO (see end)202 synchronized (this) { // BEGIN TRANSACTION !203 ScriptValueMap result = handle(match.vars());204 ScriptValue configResponseHeaders = context.getConfig().getResponseHeaders();205 responseValue = result.remove(ScriptValueMap.VAR_RESPONSE);206 responseStatusValue = result.remove(ScriptValueMap.VAR_RESPONSE_STATUS);207 responseHeaders = result.remove(ScriptValueMap.VAR_RESPONSE_HEADERS);208 afterScenario = result.remove(VAR_AFTER_SCENARIO);209 if (afterScenario == null) {210 afterScenario = context.getConfig().getAfterScenario();211 }212 configResponseHeadersMap = configResponseHeaders == null ? null : configResponseHeaders.evalAsMap(context);213 responseHeadersMap = responseHeaders == null ? null : responseHeaders.evalAsMap(context);214 } // END TRANSACTION !!215 int responseStatus = responseStatusValue == null ? 200 : Integer.valueOf(responseStatusValue.getAsString());216 HttpResponse response = new HttpResponse(startTime, System.currentTimeMillis());217 response.setStatus(responseStatus);218 if (responseValue != null && !responseValue.isNull()) {219 response.setBody(responseValue.getAsByteArray());220 }221 // trying to avoid creating a map unless absolutely necessary222 if (responseHeadersMap != null) {223 if (configResponseHeadersMap != null) {224 // this is slightly different from how the client-side configure headers works225 // here, scenarios can over-ride what the "global" hook does226 for (Map.Entry<String, Object> e : configResponseHeadersMap.entrySet()) {227 responseHeadersMap.putIfAbsent(e.getKey(), e.getValue());228 }229 }230 } else if (configResponseHeadersMap != null) {231 responseHeadersMap = configResponseHeadersMap;232 }233 if (responseHeadersMap != null) {234 responseHeadersMap.forEach((k, v) -> {235 if (v instanceof List) { // MultiValueMap returned by proceed / response.headers236 response.putHeader(k, (List) v);237 } else if (v != null) { 238 response.addHeader(k, v.toString());239 }240 }); 241 }242 if (responseValue != null && (responseHeadersMap == null || !responseHeadersMap.containsKey(HttpUtils.HEADER_CONTENT_TYPE))) {243 response.addHeader(HttpUtils.HEADER_CONTENT_TYPE, HttpUtils.getContentType(responseValue));244 } 245 if (corsEnabled) {246 response.addHeader(HttpUtils.HEADER_AC_ALLOW_ORIGIN, "*");247 }248 // functions here are outside of the 'transaction' and should not mutate global state !249 // typically this is where users can set up an artificial delay or sleep250 if (afterScenario != null && afterScenario.isFunction()) {251 afterScenario.invokeFunction(context, null);252 }253 return response;254 } 255}...

Full Screen

Full Screen

Source:HttpUtilsTest.java Github

copy

Full Screen

...9/**10 *11 * @author pthomas312 */13public class HttpUtilsTest {14 @Test15 public void testParseContentTypeCharset() {16 assertEquals(FileUtils.UTF8, HttpUtils.parseContentTypeCharset("application/json; charset=UTF-8"));17 assertEquals(FileUtils.UTF8, HttpUtils.parseContentTypeCharset("application/json; charset = UTF-8 "));18 assertEquals(FileUtils.UTF8, HttpUtils.parseContentTypeCharset("application/json; charset=UTF-8; version=1.2.3"));19 assertEquals(FileUtils.UTF8, HttpUtils.parseContentTypeCharset("application/json; charset = UTF-8 ; version=1.2.3"));20 }21 @Test22 public void testParseContentTypeParams() {23 Map<String, String> map = HttpUtils.parseContentTypeParams("application/json");24 assertNull(map);25 map = HttpUtils.parseContentTypeParams("application/json; charset=UTF-8");26 Match.equals(map, "{ charset: 'UTF-8' }");27 map = HttpUtils.parseContentTypeParams("application/json; charset = UTF-8 ");28 Match.equals(map, "{ charset: 'UTF-8' }");29 map = HttpUtils.parseContentTypeParams("application/json; charset=UTF-8; version=1.2.3");30 Match.equals(map, "{ charset: 'UTF-8', version: '1.2.3' }");31 map = HttpUtils.parseContentTypeParams("application/json; charset = UTF-8 ; version=1.2.3");32 Match.equals(map, "{ charset: 'UTF-8', version: '1.2.3' }");33 map = HttpUtils.parseContentTypeParams("application/vnd.app.test+json;ton-version=1");34 Match.equals(map, "{ 'ton-version': '1' }");35 }36 @Test37 public void testParseUriPathPatterns() {38 Map<String, String> map = HttpUtils.parseUriPattern("/cats/{id}", "/cats/1");39 Match.equals(map, "{ id: '1' }");40 map = HttpUtils.parseUriPattern("/cats/{id}/", "/cats/1"); // trailing slash41 Match.equals(map, "{ id: '1' }");42 map = HttpUtils.parseUriPattern("/cats/{id}", "/cats/1/"); // trailing slash43 Match.equals(map, "{ id: '1' }");44 map = HttpUtils.parseUriPattern("/cats/{id}", "/foo/bar");45 Match.equals(map, null);46 map = HttpUtils.parseUriPattern("/cats", "/cats/1"); // exact match47 Match.equals(map, null);48 map = HttpUtils.parseUriPattern("/{path}/{id}", "/cats/1");49 Match.equals(map, "{ path: 'cats', id: '1' }");50 map = HttpUtils.parseUriPattern("/cats/{id}/foo", "/cats/1/foo");51 Match.equals(map, "{ id: '1' }");52 }53 @Test54 public void testParseCookieString() {55 String header = "Set-Cookie: foo=\"bar\";Version=1";56 Map<String, Cookie> map = HttpUtils.parseCookieHeaderString(header);57 Match.equals(map, "{ foo: '#object' }"); // only one entry58 Match.contains(map.get("foo"), "{ name: 'foo', value: 'bar' }");59 }60 @Test61 public void testCreateCookieString() {62 Cookie c1 = new Cookie("foo", "bar");63 Cookie c2 = new Cookie("hello", "world");64 String header = HttpUtils.createCookieHeaderValue(Arrays.asList(c1, c2));65 Match.equalsText(header, "foo=bar; hello=world");66 }67}...

Full Screen

Full Screen

HttpUtils

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.HttpUtils;2import com.intuit.karate.http.HttpResponse;3import com.intuit.karate.http.HttpRequest;4import com.intuit.karate.http.Cookie;5import com.intuit.karate.http.MultiValuedMap;6import java.util.Map;7import java.util.List;8import java.util.HashMap;9import java.util.ArrayList;10import java.util.Set;11import java.util.HashSet;12import java.util.Iterator;13import java.util.UUID;14import java.util.Base64;15import java.io.ByteArrayOutputStream;16import java.io.File;17import java.io.FileInputStream;18import java.io.InputStream;19import java.io.IOException;20import java.io.ByteArrayInputStream;21import java.io.OutputStream;22import java.io.FileOutputStream;23import java.io.BufferedOutputStream;24import java.io.BufferedInputStream;25import java.io.BufferedReader;26import java.io.InputStreamReader;27import java.io.UnsupportedEncodingException;28import java.net.URL;29import java.net.URLConnection;30import java.net.HttpURLConnection;31import java.net.URLEncoder;32import java.net.MalformedURLException;33import java.nio.charset.StandardCharsets;34import java.nio.file.Files;35import java.nio.file.Path;36import java.nio.file.Paths;37import java.nio.file.StandardCopyOption;38import java.nio.file.StandardOpenOption;39import java.nio.file.FileVisitOption;40import java.nio.file.FileVisitResult;41import java.nio.file.SimpleFileVisitor;42import java.nio.file.attribute.BasicFileAttributes;43import javax.net.ssl.SSLContext;44import javax.net.ssl.TrustManager;45import javax.net.ssl.X509TrustManager;46import java.security.cert.X509Certificate;47import java.security.SecureRandom;48import java.security.NoSuchAlgorithmException;49import java.security.KeyManagementException;50import java.util.concurrent.atomic.AtomicInteger;51import java.util.concurrent.TimeUnit;52import java.util.concurrent.TimeoutException;53import java.util.concurrent.CancellationException;54import java.util.concurrent.CompletableFuture;55import java.util.concurrent.ExecutionException;56import java.util.concurrent.ExecutorService;57import java.util.concurrent.Executors;58import java.util.concurrent.ThreadFactory;59import java.util.concurrent.atomic.AtomicInteger;60import java.util.concurrent.atomic.AtomicReference;61import java.util.concurrent.atomic.AtomicBoolean;62import java.util.concurrent.locks.Lock;63import java.util.concurrent.locks.ReentrantLock;64import java.util.concurrent.locks.Condition;65import java.util.concurrent.LinkedBlockingQueue;66import java.util.concurrent.ArrayBlockingQueue;67import java.util.concurrent.BlockingQueue;68import java.util.concurrent.LinkedTransferQueue;69import java.util.concurrent.TransferQueue;70import java.util.concurrent.SynchronousQueue;71import java.util.concurrent.ConcurrentHashMap;

Full Screen

Full Screen

HttpUtils

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.HttpUtils;2import com.intuit.karate.http.HttpResponse;3import com.intuit.karate.http.HttpRequest;4import com.intuit.karate.http.MultiValuedMap;5import java.util.Map;6public class HttpUtilsExample {7 public static void main(String[] args) {8 HttpRequest request = HttpUtils.buildRequest("GET", url, null, null, null);9 HttpResponse response = HttpUtils.invoke(request);10 System.out.println("Status Code: " + response.getStatusCode());11 System.out.println("Status Text: " + response.getStatusText());12 System.out.println("Headers: " + response.getHeaders());13 System.out.println("Body: " + response.getBody());14 }15}16import com.intuit.karate.http.HttpUtils;17import com.intuit.karate.http.HttpResponse;18import com.intuit.karate.http.HttpRequest;19import com.intuit.karate.http.MultiValuedMap;20import java.util.Map;21public class HttpUtilsExample {22 public static void main(String[] args) {23 HttpRequest request = HttpUtils.buildRequest("GET", url, null, null, null);24 HttpResponse response = HttpUtils.invoke(request);25 System.out.println("Status Code: " + response.getStatusCode());26 System.out.println("Status Text: " + response.getStatusText());27 System.out.println("Headers: " + response.getHeaders());28 System.out.println("Body: " + response.getBody());29 }30}31import com.intuit.karate.http.HttpUtils;32import com.intuit.karate.http.HttpResponse;33import com.intuit.karate.http.HttpRequest;34import com.intuit.karate.http.MultiValuedMap;35import java.util.Map;36public class HttpUtilsExample {37 public static void main(String[] args) {38 HttpRequest request = HttpUtils.buildRequest("GET", url, null, null, null);39 HttpResponse response = HttpUtils.invoke(request);40 System.out.println("Status Code: " + response.getStatusCode());41 System.out.println("Status Text: " + response.getStatusText());

Full Screen

Full Screen

HttpUtils

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.HttpUtils;2import com.intuit.karate.http.HttpResponse;3import java.util.Map;4public class HttpUtilsExample {5 public static void main(String[] args) {6 Map<String, Object> map = response.asMap();7 System.out.println(map);8 }9}10import com.intuit.karate.http.HttpUtils;11import com.intuit.karate.http.HttpResponse;12import java.util.Map;13public class HttpUtilsExample {14 public static void main(String[] args) {15 Map<String, Object> map = response.asMap();16 System.out.println(map);17 }18}19import com.intuit.karate.http.HttpUtils;20import com.intuit.karate.http.HttpResponse;21import java.util.Map;22public class HttpUtilsExample {23 public static void main(String[] args) {24 Map<String, Object> map = response.asMap();25 System.out.println(map);26 }27}28import com.intuit.karate.http.HttpUtils;29import com.intuit.karate.http.HttpResponse;30import java.util.Map;31public class HttpUtilsExample {32 public static void main(String[] args) {33 Map<String, Object> map = response.asMap();34 System.out.println(map);35 }36}37import com.intuit.karate.http.HttpUtils;38import com.intuit.karate.http.HttpResponse;39import java.util.Map;40public class HttpUtilsExample {41 public static void main(String[] args) {

Full Screen

Full Screen

HttpUtils

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.HttpUtils2import com.intuit.karate.http.HttpResponse3import com.intuit.karate.http.HttpMethod4import com.intuit.karate.http.HttpConfig5def config = new HttpConfig()6config.setMethod(HttpMethod.GET)7config.setFollowRedirects(false)8config.setHeaders(['User-Agent': 'Karate', 'Accept': 'application/json'])9def response = HttpUtils.invoke(config)10import com.intuit.karate.http.HttpUtils11import com.intuit.karate.http.HttpResponse12import com.intuit.karate.http.HttpMethod13import com.intuit.karate.http.HttpConfig14def config = new HttpConfig()15config.setMethod(HttpMethod.GET)16config.setFollowRedirects(false)17config.setHeaders(['User-Agent': 'Karate', 'Accept': 'application/json'])18def response = HttpUtils.invoke(config)19assert response.headers['Content-Type'] == 'application/json; charset=utf-8'20assert response.body.contains('karate')21import com.intuit.karate.http.HttpUtils22import com.intuit.karate.http.HttpResponse23import com.intuit.karate.http.HttpMethod24import com.intuit.karate.http.HttpConfig25def config = new HttpConfig()26config.setMethod(HttpMethod.GET)27config.setFollowRedirects(false)28config.setHeaders(['User-Agent': 'Karate', 'Accept': 'application/json'])29def response = HttpUtils.invoke(config)30assert response.headers['Content-Type'] == 'application/json; charset=utf-8'31assert response.body.contains('karate')32assert response.jsonPath('$.owner.login') == 'intuit'33import com.intuit.karate.http.HttpUtils34import com.intuit.karate.http.HttpResponse35import com.intuit.k

Full Screen

Full Screen

HttpUtils

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.HttpUtils;2import java.util.Map;3import java.util.HashMap;4import java.util.List;5import java.util.ArrayList;6import java.util.Arrays;7import java.util.regex.Matcher;8import java.util.regex.Pattern;9import java.util.Base64;10import java.util.UUID;11import java.util.Date;12import java.util.Calendar;13import java.text.SimpleDateFormat;14import java.io.File;15import java.io.FileInputStream;16import java.io.FileOutputStream;17import java.io.InputStream;18import java.io.OutputStream;19import java.io.InputStreamReader;20import java.io.BufferedReader;21import java.io.BufferedWriter;22import java.io.FileWriter;23import java.io.IOException;24import java.io.Reader;25import java.nio.file.Files;26import java.nio.file.Paths;27import java.nio.charset.Charset;28import java.nio.charset.StandardCharsets;29import java.nio.file.StandardOpenOption;30import java.nio.ByteBuffer;31import java.nio.channels.FileChannel;32import java.nio.channels.FileLock;33import java.nio.channels.OverlappingFileLockException;34import com.google.gson.Gson;35import com.google.gson.GsonBuilder;36import com.google.gson.JsonObject;37import com.google.gson.JsonArray;38import com.google.gson.JsonElement;39import com.google.gson.JsonParser;40import com.google.gson.JsonSyntaxException;41import com.google.gson.reflect.TypeToken;42import org.apache.commons.io.FileUtils;43import org.apache.commons.io.FilenameUtils;44import org.apache.commons.io.IOUtils;45import org.apache.commons.io.LineIterator;46import org.apache.commons.io.output.FileWriterWithEncoding;47import org.apache.commons.io.input.ReversedLinesFileReader;48import org.apache.commons.lang3.StringUtils;49import org.apache.commons.lang3.time.DateUtils;50import org.apache.commons.lang3.time.DurationFormatUtils;51import org.apache.commons.lang3.RandomStringUtils;52import org.apache.commons.lang3.RandomUtils;53import org.apache.commons.lang3.time.StopWatch;54import org.apache.commons.lang3.tuple.Pair;55import org.apache.commons.lang3.tuple.ImmutablePair;56import org.apache.commons.text.StringEscapeUtils;57import org.apache.commons.text.WordUtils;58import org.apache.commons.text.similarity.LevenshteinDistance;59import org.apache.commons.text.similarity.JaroWinklerDistance;60import org.apache.commons.text.similarity.FuzzyScore;61import org.apache.commons.text.similarity.JaroWinklerSimilarity;62import org.apache.commons.text.similarity.LongestCommonSubsequence;63import org.apache.commons.text.similarity.LongestCommonSubsequenceDistance;64import org.apache.commons.text

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