【发布时间】:2011-06-24 15:18:02
【问题描述】:
我正在尝试发出一个 xml 发布请求,该请求期望使用 curl 来构建标题和内容的响应。这是我的代码:
<?php
function post_xml($url, $xml) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/xml; charset=utf-8"));
curl_setopt($ch, CURLOPT_USERPWD, 'myusername:mypassword');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $result;
}
$xml = '<?xml version="1.0" encoding="UTF-8"?><testing><test type="integer">1</test></testing>';
$url = "http://example.com/api/test.php";
$result = post_xml($url, $xml);
echo "<pre>"; print_r($result); echo "</pre>";
?>
要查看我的传出请求,我使用:
$info = curl_getinfo($ch);
echo($info['request_header']);
发送的结果 HTTP 请求是:
POST /api/test.php HTTP/1.1
Authorization: Basic pwmtJdCVwNEawdaODH
Host: example.com
Accept: */*
Content-Type: application/xml; charset=utf-8
Content-Length: 95
content-length 是 95,但它没有显示下面的任何 xml 内容。这会导致 422 Unprocessable Entity 错误。我完全错过了什么吗?我希望能够在发送的请求中看到 XML。
【问题讨论】:
-
问题一定出在远程 API 上;您的代码肯定是在移动数据。我使用一个脚本对其进行了测试,该脚本将原始 postbody 转储到测试文件并返回请求的哈希值,它工作得很好。
-
等等!您是在浏览器中查看此内容吗?它可能对您隐藏了 XML!试试这个而不是 print_r:
echo '<pre>', htmlentities($result), '</pre>'; -
很抱歉没有澄清,我发布的请求是原始请求。我认为这可能是我尝试使用的 API 的问题,所以我会与他们取得联系。这让我整个上午都发疯了,但我完全按照他们的文档进行操作。
-
您的功能对我来说非常完美,无需我进行任何更改。非常感谢!