Best Karate code snippet using com.intuit.karate.http.HttpRequestBuilder.buildInternal
Source:HttpRequestBuilder.java
...130 this.body = body;131 return invoke();132 }133 public HttpRequest build() {134 buildInternal();135 HttpRequest request = new HttpRequest();136 request.setMethod(method);137 request.setUrl(getUri());138 if (multiPart != null) {139 request.setBodyForDisplay(multiPart.getBodyForDisplay());140 }141 if (body != null) {142 request.setBody(JsValue.toBytes(body));143 }144 request.setHeaders(headers);145 return request;146 }147 private void buildInternal() {148 if (method == null) {149 if (multiPart != null && multiPart.isMultipart()) {150 method = "POST";151 } else {152 method = "GET";153 }154 }155 method = method.toUpperCase();156 if ("GET".equals(method) && multiPart != null) {157 Map<String, Object> parts = multiPart.getFormFields();158 if (parts != null) {159 parts.forEach((k, v) -> param(k, (String) v));160 }161 multiPart = null;162 }163 if (multiPart != null) {164 if (body == null) { // this is not-null only for a re-try, don't rebuild multi-part165 body = multiPart.build();166 String userContentType = getHeader(HttpConstants.HDR_CONTENT_TYPE);167 if (userContentType != null) {168 String boundary = multiPart.getBoundary();169 if (boundary != null) {170 contentType(userContentType + "; boundary=" + boundary);171 }172 } else {173 contentType(multiPart.getContentTypeHeader());174 }175 }176 }177 if (cookies != null && !cookies.isEmpty()) {178 List<String> cookieValues = new ArrayList<>(cookies.size());179 for (Cookie c : cookies) {180 String cookieValue = ClientCookieEncoder.LAX.encode(c);181 cookieValues.add(cookieValue);182 }183 header(HttpConstants.HDR_COOKIE, StringUtils.join(cookieValues, "; "));184 }185 if (body != null) {186 if (multiPart == null) {187 String contentType = getContentType();188 if (contentType == null) {189 ResourceType rt = ResourceType.fromObject(body);190 if (rt != null) {191 contentType = rt.contentType;192 }193 }194 Charset charset = contentType == null ? null : HttpUtils.parseContentTypeCharset(contentType);195 if (charset == null) {196 // client can be null when not in karate scenario, and mock clients can have nulls197 charset = client == null ? null : client.getConfig() == null ? null : client.getConfig().getCharset();198 if (charset != null) {199 // edge case, support setting content type to an empty string200 contentType = StringUtils.trimToNull(contentType);201 if (contentType != null) {202 contentType = contentType + "; charset=" + charset;203 }204 }205 }206 contentType(contentType);207 }208 }209 }210 public Response invoke() {211 return client.invoke(build());212 }213 public boolean isRetry() {214 return retryUntil != null;215 }216 public String getRetryUntil() {217 return retryUntil;218 }219 public void setRetryUntil(String retryUntil) {220 this.retryUntil = retryUntil;221 }222 public HttpRequestBuilder url(String value) {223 url = value;224 return this;225 }226 public HttpRequestBuilder method(String method) {227 this.method = method;228 return this;229 }230 public HttpRequestBuilder paths(String... paths) {231 for (String path : paths) {232 path(path);233 }234 return this;235 }236 public HttpRequestBuilder path(String path) {237 if (path == null) {238 return this;239 }240 if (paths == null) {241 paths = new ArrayList<>();242 }243 paths.add(path);244 return this;245 }246 public String getUri() {247 try {248 URIBuilder builder;249 if (url == null) {250 builder = new URIBuilder();251 } else {252 builder = new URIBuilder(url);253 }254 if (params != null) {255 params.forEach((key, values) -> values.forEach(value -> builder.addParameter(key, value)));256 }257 if (paths != null) {258 List<String> segments = new ArrayList();259 for (String item : builder.getPathSegments()) {260 if (!item.isEmpty()) {261 segments.add(item);262 }263 }264 Iterator<String> pathIterator = paths.iterator();265 while (pathIterator.hasNext()) {266 String item = pathIterator.next();267 if (!pathIterator.hasNext() && "/".equals(item)) { // preserve trailing slash268 segments.add("");269 } else {270 for (String s : StringUtils.split(item, '/', true)) {271 segments.add(s);272 }273 }274 }275 builder.setPathSegments(segments);276 }277 URI uri = builder.build();278 return uri.toASCIIString();279 } catch (URISyntaxException e) {280 throw new RuntimeException(e);281 }282 }283 public HttpRequestBuilder body(Object body) {284 this.body = body;285 return this;286 }287 public HttpRequestBuilder bodyJson(String json) {288 this.body = Json.of(json).value();289 return this;290 }291 public List<String> getHeaderValues(String name) {292 return StringUtils.getIgnoreKeyCase(headers, name); // TODO optimize293 }294 public String getHeader(String name) {295 List<String> list = getHeaderValues(name);296 if (list == null || list.isEmpty()) {297 return null;298 } else {299 return list.get(0);300 }301 }302 public String getContentType() {303 return getHeader(HttpConstants.HDR_CONTENT_TYPE);304 }305 public HttpRequestBuilder removeHeader(String name) {306 if (headers != null) {307 StringUtils.removeIgnoreKeyCase(headers, name);308 }309 return this;310 }311 public HttpRequestBuilder header(String name, String... values) {312 return header(name, Arrays.asList(values));313 }314 public HttpRequestBuilder header(String name, List<String> values) {315 if (headers == null) {316 headers = new LinkedHashMap<>();317 }318 for (String key : headers.keySet()) {319 if (key.equalsIgnoreCase(name)) {320 name = key;321 break;322 }323 }324 headers.put(name, values);325 return this;326 }327 public HttpRequestBuilder header(String name, String value) {328 return header(name, Collections.singletonList(value));329 }330 public HttpRequestBuilder headers(Map<String, Object> map) {331 map.forEach((k, v) -> {332 if (!k.startsWith(":")) { // strip (armeria) special headers333 if (v instanceof List) {334 header(k, (List) v);335 } else if (v != null) {336 header(k, v.toString());337 }338 }339 });340 return this;341 }342 public HttpRequestBuilder headers(Value value) {343 JsValue jv = new JsValue(value);344 if (jv.isObject()) {345 headers(jv.getAsMap());346 } else {347 logger.warn("unexpected headers() argument: {}", value);348 }349 return this;350 }351 public HttpRequestBuilder contentType(String contentType) {352 if (contentType != null) {353 header(HttpConstants.HDR_CONTENT_TYPE, contentType);354 }355 return this;356 }357 public List<String> getParam(String name) {358 if (params == null || name == null) {359 return null;360 }361 return params.get(name);362 }363 public HttpRequestBuilder param(String name, String... values) {364 return param(name, Arrays.asList(values));365 }366 public HttpRequestBuilder param(String name, List<String> values) {367 if (params == null) {368 params = new HashMap<>();369 }370 List<String> notNullValues = values.stream().filter(v -> v != null).collect(Collectors.toList());371 if (!notNullValues.isEmpty()) {372 params.put(name, notNullValues);373 }374 return this;375 }376 public HttpRequestBuilder params(Map<String, List<String>> params) {377 this.params = params;378 return this;379 }380 public HttpRequestBuilder cookies(Collection<Map> cookies) {381 for (Map<String, Object> map : cookies) {382 cookie(map);383 }384 return this;385 }386 public HttpRequestBuilder cookie(Map<String, Object> map) {387 return cookie(Cookies.fromMap(map));388 }389 public HttpRequestBuilder cookie(Cookie cookie) {390 if (cookies == null) {391 cookies = new HashSet<>();392 }393 cookies.add(cookie);394 return this;395 }396 public HttpRequestBuilder cookie(String name, String value) {397 return cookie(new DefaultCookie(name, value));398 }399 public HttpRequestBuilder formField(String name, Object value) {400 if (multiPart == null) {401 multiPart = new MultiPartBuilder(false, client);402 }403 multiPart.part(name, value);404 return this;405 }406 public HttpRequestBuilder multiPartJson(String json) {407 return multiPart(Json.of(json).value());408 }409 public HttpRequestBuilder multiPart(Map<String, Object> map) {410 if (multiPart == null) {411 multiPart = new MultiPartBuilder(true, client);412 }413 multiPart.part(map);414 return this;415 }416 //==========================================================================417 //418 private final Methods.FunVar PATH_FUNCTION = args -> {419 if (args.length == 0) {420 return getUri();421 } else {422 for (Object o : args) {423 if (o != null) {424 path(o.toString());425 }426 }427 return this;428 }429 };430 private static String toString(Object o) {431 return o == null ? null : o.toString();432 }433 private final Methods.FunVar PARAM_FUNCTION = args -> {434 if (args.length == 1) {435 List<String> list = getParam(toString(args[0]));436 if (list == null || list.isEmpty()) {437 return null;438 }439 return list.get(0);440 } else {441 param(toString(args[0]), toString(args[1]));442 return this;443 }444 };445 private final Methods.FunVar HEADER_FUNCTION = args -> {446 if (args.length == 1) {447 return getHeader(toString(args[0]));448 } else {449 header(toString(args[0]), toString(args[1]));450 return this;451 }452 };453 private final Methods.FunVar INVOKE_FUNCTION = args -> {454 switch (args.length) {455 case 0:456 return invoke();457 case 1:458 return invoke(args[0].toString());459 default:460 return invoke(args[0].toString(), args[1]);461 }462 };463 private final Methods.FunVar METHOD_FUNCTION = args -> {464 if (args.length > 0) {465 return method((String) args[0]);466 } else {467 return method;468 }469 };470 private final Methods.FunVar BODY_FUNCTION = args -> {471 if (args == null) { // can be null472 return this;473 }474 if (args.length > 0) {475 return body(args[0]);476 } else {477 return JsValue.fromJava(body);478 }479 };480 private final Supplier GET_FUNCTION = () -> invoke(GET);481 private final Function POST_FUNCTION = o -> invoke(POST, o);482 private final Function PUT_FUNCTION = o -> invoke(PUT, o);483 private final Function PATCH_FUNCTION = o -> invoke(PATCH, o);484 private final Supplier DELETE_FUNCTION = () -> invoke(DELETE);485 @Override486 public Object getMember(String key) {487 switch (key) {488 case METHOD:489 return METHOD_FUNCTION;490 case PATH:491 return PATH_FUNCTION;492 case HEADER:493 return HEADER_FUNCTION;494 case HEADERS:495 return JsValue.fromJava(headers);496 case PARAM:497 return PARAM_FUNCTION;498 case PARAMS:499 return JsValue.fromJava(params);500 case BODY:501 return BODY_FUNCTION;502 case INVOKE:503 return INVOKE_FUNCTION;504 case GET:505 return GET_FUNCTION;506 case POST:507 return POST_FUNCTION;508 case PUT:509 return PUT_FUNCTION;510 case PATCH:511 return PATCH_FUNCTION;512 case DELETE:513 return DELETE_FUNCTION;514 case URL:515 return (Function<String, Object>) this::url;516 case MULTI_PART:517 return (Function<Map<String, Object>, Object>) this::multiPart;518 default:519 logger.warn("no such property on http object: {}", key);520 return null;521 }522 }523 @Override524 public void putMember(String key, Value value) {525 switch (key) {526 case METHOD:527 method = value.asString();528 break;529 case BODY:530 body = JsValue.toJava(value);531 break;532 case HEADERS:533 headers(value);534 break;535 case PARAMS:536 params = (Map) JsValue.toJava(value);537 break;538 case URL:539 url = value.asString();540 break;541 default:542 logger.warn("put not supported on http object: {} - {}", key, value);543 }544 }545 @Override546 public Object getMemberKeys() {547 return KEY_ARRAY;548 }549 @Override550 public boolean hasMember(String key) {551 return KEY_SET.contains(key);552 }553 @Override554 public String toString() {555 return getUri();556 }557 public String toCurlCommand() {558 buildInternal();559 StringBuilder sb = new StringBuilder();560 sb.append("curl ");561 String url = getUri();562 if (!StringUtils.isBlank(url)) {563 sb.append(getUri()).append(' ');564 }565 sb.append("\\\n");566 if (multiPart != null) {567 sb.append(multiPart.toCurlCommand());568 } else if (body != null) {569 String raw = JsValue.toString(body);570 sb.append("-d '").append(raw).append("'");571 }572 return sb.toString();573 }574 public Map<String, Object> toMap() {575 buildInternal();576 Map<String, Object> map = new HashMap();577 map.put("url", getUri());578 map.put("method", method);579 if (headers != null) {580 List<Map> list = new ArrayList(headers.size());581 map.put("headers", list);582 headers.forEach((k, v) -> {583 if (v != null) {584 v.forEach(value -> {585 if (value != null) {586 Map<String, Object> header = new HashMap();587 header.put("name", k);588 header.put("value", value);589 list.add(header);...
buildInternal
Using AI Code Generation
1def response = com.intuit.karate.http.HttpRequestBuilder()2 .buildInternal()3def response = com.intuit.karate.http.HttpRequestBuilder()4 .build()5def response = com.intuit.karate.http.HttpRequestBuilder()6 .build()7def response = com.intuit.karate.http.HttpRequestBuilder()8 .build()9def response = com.intuit.karate.http.HttpRequestBuilder()10 .build()11def response = com.intuit.karate.http.HttpRequestBuilder()12 .build()13def response = com.intuit.karate.http.HttpRequestBuilder()14 .build()15def response = com.intuit.karate.http.HttpRequestBuilder()16 .build()17def response = com.intuit.karate.http.HttpRequestBuilder()18 .build()19def response = com.intuit.karate.http.HttpRequestBuilder()20 .build()21def response = com.intuit.karate.http.HttpRequestBuilder()22 .build()
buildInternal
Using AI Code Generation
1 * def request = com.intuit.karate.http.HttpRequestBuilder.buildInternal('GET', url, null)2 * request.addHeader('Content-Type', 'application/json')3 * request.addHeader('Accept', 'application/json')4 * request.addHeader('User-Agent', 'Karate')5 * request.addHeader('Connection', 'keep-alive')6 * request.addHeader('Accept-Encoding', 'gzip, deflate, br')7 * request.addHeader('Accept-Language', 'en-US,en;q=0.9')8 * request.addHeader('Cache-Control', 'no-cache')9 * request.addHeader('Pragma', 'no-cache')10 * request.addHeader('Sec-Fetch-Dest', 'document')11 * request.addHeader('Sec-Fetch-Mode', 'navigate')12 * request.addHeader('Sec-Fetch-Site', 'none')13 * request.addHeader('Sec-Fetch-User', '?1')14 * request.addHeader('Upgrade-Insecure-Requests', '1')15 * request.addHeader('Cookie', '_ga=GA1.2.1378305892.1594405748; _gid=GA1.2.1692021717.1594405748; _gat=1')16 * def response = com.intuit.karate.http.HttpClient.sendInternal(request)17 * response.headers['Content-Type'] == 'application/json; charset=utf-8'
buildInternal
Using AI Code Generation
1def response = karate.callSingle('classpath:com/intuit/karate/http/http-request-builder.feature', {2 })3 response.jsonPath('$.request.method').contains('GET')4 response.jsonPath('$.request.headers').contains('Content-Type: application/json')5 response.jsonPath('$.request.body').contains('null')6 response.jsonPath('$.response.status').contains(200)7 response.jsonPath('$.response.headers').contains('Content-Type: application/json')8 response.jsonPath('$.response.body').contains('{"message":"hello world"}')9}
buildInternal
Using AI Code Generation
1import com.intuit.karate.http.HttpRequestBuilder2import com.intuit.karate.http.HttpResponse3import com.intuit.karate.http.HttpMethod4def request = new HttpRequestBuilder()5request.buildInternal('soap-request.xml')6def response = request.invoke()7import com.intuit.karate.http.HttpRequestBuilder8import com.intuit.karate.http.HttpResponse9import com.intuit.karate.http.HttpMethod10def request = new HttpRequestBuilder()11def response = request.invoke()12import com.intuit.karate.http.HttpRequestBuilder13import com.intuit.karate.http.HttpResponse14import com.intuit.karate.http.HttpMethod15def request = new HttpRequestBuilder()16request.buildInternal([a: 'b'])17def response = request.invoke()18import com.intuit.karate.http.HttpRequestBuilder19import com.intuit.karate.http.HttpResponse20import com.intuit.karate.http.HttpMethod21def request = new HttpRequestBuilder()22request.buildInternal(['a', 'b'])23def response = request.invoke()24import com.intuit.karate.http.HttpRequest
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!!