![](/img/trans.png)
[英]Php CURL Though I set the header as application/json the request goes as 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的文檔,並且他們指定我需要將標頭設置為“ application / x-www-form-urlencoded”,但我必須以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();
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>
手動添加標頭,以便您可以指定要發送並想要返回XML
您不必對XML進行URL編碼。
另外,后字段應該只是XML。 不是XML = $ xmlcontent
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.