使用 x-www-form-urlencoded 请求正文发出 MarkLogic xdmp:http-post() 请求

Making a MarkLogic xdmp:http-post() request with x-www-form-urlencoded request body

我如何发送一个 xdmp:http-post() 请求,该请求具有带有两个键值对的 x-www-form-urlencoded 请求正文?

示例请求:

let $request-body := <key-value-pairs>
                      <foo>bar</foo>
                      <bar>foo</bar>
                    <key-value-pairs>

return
xdmp:http-post("https://myendpoint.com", 
              <options xmlns="xdmp:http">
                <headers>
                  <Content-type>application/x-www-form-urlencoded</Content-type>
                </headers>
                <data>{$request-body}</data>
              </options>)

不幸的是,这不在 MarkLogic 文档中: https://docs.marklogic.com/xdmp:http-post

这应该有效:

let $request-body := "foo=bar&amp;bar=foo"
return xdmp:http-post("https://myendpoint.com", 
          <options xmlns="xdmp:http">
            <headers>
              <Content-Type>application/x-www-form-urlencoded</Content-Type>
            </headers>
            <data>{$request-body}</data>
          </options>)

Rob 的回答是正确的,但我建议计算 request-body,并正确应用 encode-for-uri。类似于:

let $form-data := <key-value-pairs>
                      <foo>bar</foo>
                      <bar>foo</bar>
                    </key-value-pairs>
let $request-body := string-join(
  for $pair in $form-data/*
  let $key := name($pair)
  let $val := data($pair)
  return (encode-for-uri($key) || '=' || encode-for-uri($val)),
  '&amp;'
)
return $request-body