如何解决fsockopen将不发送发布数据
| 已解决:问题属于内容类型。本来应该Content-Type: application/x-www-form-urlencoded
帮助链接:http://www.bradino.com/PHP/empty-post-array/
我似乎无法收到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);
}
解决方法
您应该考虑使用内置的cURL库。
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,$host . ( ! empty($path) ? $path : \'/\' ) . ( ! empty($params) ? \'?\' . $params : null ));
$result = curl_exec($ch);
curl_close($ch);
return explode(\"\\r\\n\\r\\n\",$result,2);
}
上面的函数将返回一个包含标题和正文的数组。
, 这有帮助吗?
更改
fputs($socket,\"Content-type: text/xml\\r\\n\");
至
fputs($socket,\"Content-type: application/x-www-form-urlencoded\\r\\n\");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。