已解决:问题出现在Content-type中。应该是
Content-Type: application/x-www-form-urlencoded
我似乎无法获取POST
数据。我已经梳理了这个方法一段时间,每次运行测试时,$_POST
数组都是空的。
$output = new SimpleXMLElement($xml);
$params = "method=updateOrder&xml=".$output;
$response = Rest::Post("example.com", 80, "/resource/path.php", $params);
上面是我静态调用的另一种方法,它使用所需的方法创建HttpRequest
。下面是获取子调用并传递相同数据但包含方法名称的方法。 IE:POST
。
private static function httpRequest($host, $port, $method, $path, $params)
{
//Check method
if(empty($method))
$method = "GET";
$method = strtoupper($method);
//Port
if(empty($port))
$port = 80;
//Build Querystring
$data = "";
if(!empty($params) && $method == "GET")
foreach($params as $name => $value)
{
$data .= $name . "=" . urlencode($value) . "&";
}
if($method == "GET" && !empty($data))
$path .= "?" . $data;
//connection
$socket = fsockopen($host, $port);
if(!$socket)
die("Socket failed, no connection.");
//Write Data and headers to stream
fputs($socket, $method ." ". $path . " HTTP/1.1\r\n");
fputs($socket, "Host: " . $host . "\r\n");
if($method === "POST")
{
fputs($socket, "Content-type: text/xml\r\n");
fputs($socket, "Content-length: " . strlen($params) . "\r\n");
}
fputs($socket, "Connection: close\r\n\r\n");
//Write body
if($method === "POST")
fputs($socket, $params);
//Gets headers
$responseHeader = "";
do
{
$responseHeader .= fgets($socket, 1024);
}
while(strpos($responseHeader, "\r\n\r\n") === false);
//Gets body
$responseBody = "";
while(!feof($socket))
$responseBody .= fgets($socket, 1024);
//Done & return
fclose($socket);
return array(0=>$responseHeader, 1=>$responseBody);
}
答案 0 :(得分:0)
您应该考虑使用built-in cURL library。
function httpRequest($host, $port = 80, $method = 'GET', $path = '/', $params = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ( ! empty($port) )
curl_setopt($ch, CURLOPT_PORT, $port);
if ( ! empty($method) && $method == 'POST' )
{
curl_setopt($ch, CURLOPT_URL, $host . ( ! empty($path) ? $path : '/' ));
curl_setopt($ch, CURLOPT_POST, TRUE);
if ( ! empty($params) )
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
else
curl_setopt($ch, CURLOPT_URL, $host . ( ! empty($path) ? $path : '/' ) . ( ! empty($params) ? '?' . $params : null ));
$result = curl_exec($ch);
curl_close($ch);
return explode("\r\n\r\n", $result, 2);
}
上面的函数将返回一个包含标题和正文的数组。
答案 1 :(得分:0)
这有帮助吗?
更改
fputs($socket, "Content-type: text/xml\r\n");
到
fputs($socket, "Content-type: application/x-www-form-urlencoded\r\n");