如何在基于 XML 的 API 调用中将 headers 设置为 "application/x-www-form-urlencoded"

How do I set the headers to "application/x-www-form-urlencoded" on a XML based API Call

我正在查看 VerMail API 的文档,他们指定我需要将 headers 设置为 "application/x-www-form-urlencoded",但我必须将数据发送为 [=25] =].. 我知道如果我将数据发送到数组中,这是自动的,但是我将如何使用 XML 来做到这一点?

这是我目前的代码:

$xmlcontent = "
<api>
  <authentication>
    <api_key>".$apiKey."</api_key>
    <shared_secret>".$apiSecret."</shared_secret>
    <response_type>xml</response_type>
  </authentication>

  <data>
    <methodCall>
      <methodname>legacy.message_stats</methodname>
      <last>100</last>
    </methodCall>
  </data>
</api>
";

$xmlcontent = urlencode($xmlcontent);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent);
$content = curl_exec($ch);

print_r($content);

这是我在 运行 时在源代码上看到的内容:

HTTP/1.1 200 OK
Date: Fri, 23 Jan 2015 20:17:52 GMT
Server: Apache
Cache-Control: max-age=18000
Expires: Sat, 24 Jan 2015 01:17:52 GMT
Content-Length: 595
Connection: close
Content-Type: text/xml;charset=utf-8
Set-Cookie: BIGipServerBH-gen-80=235023882.20480.0000; path=/

<?xml version="1.0" encoding="utf-8"?>
<methodResponse><item><error><![CDATA[1]]></error><responseText><![CDATA[ XML Error: Please verify the XML request is valid.  For special characters please ensure you are using <![CDATA[ ]]]]><![CDATA[> blocks and url encoding data properly.]]></responseText><responseData><error><![CDATA[Not well-formed (invalid token) at line: 1]]></error><responseCode><![CDATA[425]]></responseCode></responseData><responseNum><![CDATA[1]]></responseNum><totalRequests><![CDATA[0]]></totalRequests><totalCompleted><![CDATA[0]]></totalCompleted></item></methodResponse>

手动添加 headers 这样您就可以指定您要发送和要回 XML

您不必对 xml.

进行 URL 编码

此外,postfields 应该只是 XML。不是 XML=$xml内容

$xmlcontent = "
<api>
  <authentication>
    <api_key>".$apiKey."</api_key>
    <shared_secret>".$apiSecret."</shared_secret>
    <response_type>xml</response_type>
  </authentication>

  <data>
    <methodCall>
      <methodname>legacy.message_stats</methodname>
      <last>100</last>
    </methodCall>
  </data>
</api>
";

$xmlcontent = urlencode($xmlcontent);

$ch = curl_init();

$headers = array(
                "Content-type: text/xml;charset=\"utf-8\"",
                "Accept: text/xml",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "Content-length: ".strlen($xmlcontent),
            );
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlcontent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$content = curl_exec($ch);