If request body was JSON or XML, use "equalToJson" or "equalToXml" (respectively) in the RequestPattern so it's
easier to read. Otherwise, just use "equalTo"
343842
@Override
    public ContentPattern<?> forRequest(Request request) {
        final String mimeType = request.getHeaders().getContentTypeHeader().mimeTypePart();
        if (mimeType != null) {
            if (mimeType.contains("json")) {
                return new EqualToJsonPattern(request.getBodyAsString(), ignoreArrayOrder, ignoreExtraElements);
            } else if (mimeType.contains("xml")) {
                return new EqualToXmlPattern(request.getBodyAsString());
            } else if (mimeType.equals("multipart/form-data")) {
                // TODO: Need to add a matcher that can handle multipart data properly. For now, just always match
                return new AnythingPattern();
            } else if (!determineIsTextFromMimeType(mimeType)) {
                return new BinaryEqualToPattern(request.getBody());
            }
        }

        return new EqualToPattern(request.getBodyAsString(), caseInsensitive);
    }
466195
function(request) {
        var doc = request.responseXML;
        if (!doc || !doc.documentElement) {
            doc = request.responseText;
        }
        if (!doc || doc.length <= 0) {
            return null;
        }
        return this.format.read(doc);
    }
1330136
function deserialiseRequest (serialised) {
  var options
  var url

  if (typeof serialised === 'string') {
    options = JSON.parse(serialised)
    url = options.url
  } else if (typeof serialised === 'object') {
    options = serialised
    url = options.url
  } else {
    throw new Error('Expecting serialised request to be a string or object')
  }

  const request = new Request(url, options)

  const properties = {
    context: {
      enumerable: true,
      value: options.context
    }
  }

  const methods = Object.keys(BodyTypes).reduce(function (obj, key) {
    const methodName = BodyMethods[key]
    obj[methodName] = {
      enumerable: true,
      value: function () {
        if (request.bodyUsed) {
          return Promise.reject(new TypeError('Already used'))
        }
        request.bodyUsed = true
        return Promise.resolve(remakeBody(options.__body, key))
      }
    }
    return obj
  }, properties)

  Object.defineProperties(request, methods)

  return request
}
1320489
@Override
    @Nullable
    public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
                                 Class<?> expectedResultType) throws Exception {

        final MediaType contentType = request.contentType();
        if (contentType != null && (contentType.is(MediaType.JSON) ||
                                    contentType.subtype().endsWith("+json"))) {
            final ObjectReader reader = readers.computeIfAbsent(expectedResultType, mapper::readerFor);
            if (reader != null) {
                final String content = request.content(contentType.charset().orElse(StandardCharsets.UTF_8));
                try {
                    return reader.readValue(content);
                } catch (JsonProcessingException e) {
                    throw new IllegalArgumentException("failed to parse a JSON document: " + e, e);
                }
            }
        }
        return RequestConverterFunction.fallthrough();
    }
1105515
public static Map<String, Object> convertRequestToMap(
            HttpServletRequest request) throws IOException, ServletException, JSONFormatException {

        Map<String, Object> inParams = new HashMap<String, Object>();

        //GET
        String q = request.getQueryString();
        if(!org.s1.objects.Objects.isNullOrEmpty(q)){
            String [] arr = q.split("&");
            for(String it:arr){
                String nv [] = it.split("=");
                String n = nv[0];
                String v = null;
                if(nv.length>1) {
                    v = nv[1];
                    try {
                        v = URLDecoder.decode(v, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        throw S1SystemError.wrap(e);
                    }
                }
                if(PARAMS_PARAMETER.equals(n)){
                    inParams.putAll(Objects.fromWire(JSONFormat.evalJSON(v)));
                }else{
                    inParams.put(n,v);
                }
            }
        }
        if (request.getContentType()!=null && request.getContentType().contains("application/json")) {
            //JSON
            String s = IOUtils.toString(request.getInputStream(), "UTF-8");
            inParams = JSONFormat.evalJSON(s);
        } else if (request.getContentType()!=null
                && request.getContentType().contains("application/x-www-form-urlencoded")
                ) {
            //POST
            Iterator<Map.Entry<String, String[]>> it = request
                    .getParameterMap().entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String[]> e = it.next();
                String v = "" + e.getValue()[0];
                inParams.put(e.getKey(), v);
            }
        } else if (request.getContentType()!=null
                && request.getContentType().contains("multipart/form-data")
                ) {
            //parts
            for(Part p : request.getParts()){
                if(p.getContentType()!=null){
                    if(p.getSize()==0)
                        continue;
                    String name = p.getName();
                    //file
                    for (String content : p.getHeader("content-disposition").split(";")) {
                        if (content.trim().startsWith("filename")) {
                            name = content.substring(
                                    content.indexOf('=') + 1).trim().replace("\"", "");
                        }
                    }
                    String ext = "";
                    int ei = name.lastIndexOf(".");
                    if(ei!=-1 && ei<name.length()-1){
                        ext = name.substring(ei+1);
                        name = name.substring(0,ei);
                    }

                    inParams.put(p.getName(), new FileParameter(p.getInputStream(),name,ext,p.getContentType(),p.getSize()));
                }else{
                    //param
                    inParams.put(p.getName(), IOUtils.toString(p.getInputStream(),"UTF-8"));
                }
            }
        }
        inParams = Objects.fromWire(inParams);
        return inParams;
    }
983350
def with_json(self, data=None, **params):
        
        if isinstance(data, (tuple, list)):
            data = dict(data)

        if params:
            # data must be None or able to be a dict
            if isinstance(data, dict):
                data.update(params)
            elif data is None:
                data = params
            else:
                raise ValueError('Data must be None or a dict if used with params, got: %r' % data)

        req = self.with_headers({'Content-Type': 'application/json', 'Accept': 'application/json'})
        if isinstance(data, basestring):
            # Looks like it's already been encoded
            return req.with_body(data)
        else:
            return req.with_body(json.dumps(data))
140901
private String patchedJsonBody(WebSocketContext context) {
        String body = context.stringMessage();
        if (S.blank(body) || 1 < fieldsAndParamsCount) {
            return body;
        }
        String theName = singleJsonFieldName(context);
        int theNameLen = theName.length();
        if (null == theName) {
            return body;
        }
        body = body.trim();
        boolean needPatch = body.charAt(0) == '[';
        if (!needPatch) {
            if (body.charAt(0) != '{') {
                throw new IllegalArgumentException("Cannot parse JSON string: " + body);
            }
            boolean startCheckName = false;
            int nameStart = -1;
            for (int i = 1; i < body.length(); ++i) {
                char c = body.charAt(i);
                if (c == ' ') {
                    continue;
                }
                if (startCheckName) {
                    if (c == '"') {
                        break;
                    }
                    int id = i - nameStart - 1;
                    if (id >= theNameLen || theName.charAt(i - nameStart - 1) != c) {
                        needPatch = true;
                        break;
                    }
                } else if (c == '"') {
                    startCheckName = true;
                    nameStart = i;
                }
            }
        }
        return needPatch ? S.fmt("{\"%s\": %s}", theName, body) : body;
    }
1235092
function () {
        if (req.status !== 200) {
          console.warn(req.responseText);
          return;
        }
        // Show the raw response text on page
        xmlOutput.textContent = req.responseText;
        // convert XML to javascript objects
        var json = sdmxmllib.mapSDMXMLResponse(req.responseText);
        // Convert to json and show on page
        jsonOutput.textContent = JSON.stringify(json, null, 2);
    }
1072741
function(json, next) {
                fs.writeFile(out + "/" + path.basename(url).replace('.xml', '.json'), JSON.stringify(json), function (err) {
                    if (err) {
                        return next(err);
                    }
                    next(null, json);
                });
            }
659852
@Override
    public String evaluate(String request) throws EvaluationException {
        logger.debug("evaluating request: {}", request);

        RequestCtx req = null;
        ByteArrayInputStream is = new ByteArrayInputStream(request.getBytes());

        try {
            req = BasicRequestCtx.getInstance(is);
        } catch (ParsingException pe) {
            logger.error("Error parsing request:\n" + request, pe);
            throw new EvaluationException("Error parsing request:\n" + request);
        }

        ResponseCtx res = evaluate(req);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        res.encode(os, new Indenter());

        if (logger.isDebugEnabled()) {
            logger.debug("response is: {}", os.toString());
        }
        return os.toString();
    }
165353
function xml2jsonRecurse(xmlStr) {
    var obj = {},
        tagName, indexClosingTag, inner_substring, tempVal, openingTag;

    while (xmlStr.match(/<[^\/][^>]*>/)) {
        openingTag = xmlStr.match(/<[^\/][^>]*>/)[0];
        tagName = openingTag.substring(1, openingTag.length - 1);
        indexClosingTag = xmlStr.indexOf(openingTag.replace('<', '</'));

        // account for case where additional information in the openning tag
        if (indexClosingTag == -1) {

            tagName = openingTag.match(/[^<][\w+$]*/)[0];
            indexClosingTag = xmlStr.indexOf('</' + tagName);
            if (indexClosingTag == -1) {
                indexClosingTag = xmlStr.indexOf('<\\/' + tagName);
            }
        }
        inner_substring = xmlStr.substring(openingTag.length, indexClosingTag);
        if (inner_substring.match(/<[^\/][^>]*>/)) {
            tempVal = xml2json(inner_substring);
        }
        else {
            tempVal = inner_substring;
        }
        // account for array or obj //
        if (obj[tagName] === undefined) {
            obj[tagName] = tempVal;
        }
        else if (Array.isArray(obj[tagName])) {
            obj[tagName].push(tempVal);
        }
        else {
            obj[tagName] = [obj[tagName], tempVal];
        }

        xmlStr = xmlStr.substring(openingTag.length * 2 + 1 + inner_substring.length);
    }

    return obj;
}
1248925
def _request_json(
    url,
    parameters=None,
    body=None,
    headers=None,
    cache=True,
    agent=None,
    reattempt=5,
):
    
    assert url
    content = None
    status = 500
    log.info("url: %s" % url)

    if isinstance(headers, dict):
        headers = _clean_dict(headers)
    else:
        headers = dict()
    if isinstance(parameters, dict):
        parameters = _d2l(_clean_dict(parameters))
    if body:
        method = "POST"
        headers["content-type"] = "application/json"
        headers["user-agent"] = _get_user_agent(agent)
        headers["content-length"] = ustr(len(body))
    else:
        method = "GET"
        headers["user-agent"] = _get_user_agent(agent)

    initial_cache_state = SESSION._is_cache_disabled  # yes, i'm a bad person
    try:
        SESSION._is_cache_disabled = not cache
        response = SESSION.request(
            url=url,
            params=parameters,
            json=body,
            headers=headers,
            method=method,
            timeout=1,
        )
        status = response.status_code
        content = response.json() if status // 100 == 2 else None
        cache = getattr(response, "from_cache", False)
    except RequestException as e:
        log.debug(e, exc_info=True)
        return _request_json(
            url, parameters, body, headers, cache, agent, reattempt - 1
        )
    except Exception as e:
        log.error(e, exc_info=True)
        if reattempt > 0:
            SESSION.cache.clear()
            return _request_json(
                url, parameters, body, headers, False, agent, 0
            )
    else:
        log.info("method: %s" % method)
        log.info("headers: %r" % headers)
        log.info("parameters: %r" % parameters)
        log.info("cache: %r" % cache)
        log.info("status: %d" % status)
        log.debug("content: %s" % content)
    finally:
        SESSION._is_cache_disabled = initial_cache_state

    return status, content
1217572
private boolean shouldPrettyPrint(HttpRequest request) {
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri(), Charsets.UTF_8, true, 2);
    Map<String, List<String>> parameters = decoder.parameters();
    if (parameters.containsKey(PP_PARAMETER)) {
      return parseBoolean(parameters.get(PP_PARAMETER).get(0));
    } else if (parameters.containsKey(PRETTY_PRINT_PARAMETER)) {
      return parseBoolean(parameters.get(PRETTY_PRINT_PARAMETER).get(0));
    }
    return true;
  }
445322
function (query) {
	this.toXml = function () {
		return {
			"NPANXXSearchAndOrderType": {
				"NpaNxx": {_text: query.npaNxx},
				"EnableTNDetail": {_text: query.enableTnDetail || query.enableTNDetail},
				"EnableLCA": {_text: query.enableLca || query.enableLCA},
				"Quantity": {_text: query.quantity || 1}
			}
		};
	};
}
39179
function parseBodyParam (req, res, next) {
  let params = getParams(req);

  params.some((param) => {
    if (param.in === "body") {
      util.debug('    Parsing the "%s" body parameter', param.name);

      if (_.isPlainObject(req.body) && _.isEmpty(req.body)) {
        if (param.type === "string" || (param.schema && param.schema.type === "string")) {
          // Convert {} to ""
          req.body = "";
        }
        else {
          // Convert {} to undefined
          req.body = undefined;
        }
      }

      // Parse the body
      req.body = parseParameter(param, req.body, param.schema);

      // There can only be one "body" parameter, so skip the rest
      return true;
    }
  });

  // If there are no body/formData parameters, then reset `req.body` to undefined
  if (params.length > 0) {
    let hasBody = params.some((param) => {
      return param.in === "body" || param.in === "formData";
    });

    if (!hasBody) {
      req.body = undefined;
    }
  }

  next();
}
934116
public static String objectJsonBody(Object body) {
		if (body instanceof String)
			return (String) body;
		String txt = "";
		try {
			txt = mapper.writeValueAsString(body);
		} catch (JsonProcessingException e) {
			log.error("objectJsonBody", e);
		}
		return txt;
	}
11748
function makeHttpRequest(encoding, next) {
  var start = Date.now();

  request(
    {
      url: 'http://localhost:1337/' + encoding,
      method: 'GET',
      headers: {
        'accept-encoding': encoding,
      },
    },
    function(err, data, body) {
      var time = Date.now() - start;

      console.log(encoding.toUpperCase() + ' COMPRESSION:');
      console.log('  status:', data.statusCode);
      console.log('  body  :', body);
      console.log('  time  :', time);

      common.verify(function() {
        data.headers.should.not.have.property('content-encoding');
        body.should.equal('hello, ' + encoding);
      });

      console.log();

      next();
    }
  );
}