使用PHP + cURL的HTTP POST请求

时间:2014-02-16 12:16:33

标签: c# php curl

我正在尝试使用PHP + cURL创建HTTP post请求,这相当于文件“SendToast.aspx.cs”提到的here示例

我的PHP文件如下所示,

<?php 

$uri      = $_POST["uri"];
$title    = $_POST["title"]; 
$subtitle = $_POST["subtitle"];


$file = 'file.txt';
//phpinfo();
$theData = '<?xml version="1.0" encoding="utf-8"?>\\r';
$theData .= "<wp:Notification xmlns:wp=\"WPNotification\">";
$theData .=  "<wp:Toast>";
$theData .=  "<wp:Text1>" .$title;
$theData .=  "</wp:Text1>";
$theData .=  "<wp:Text2>" .$subtitle;
$theData .=  "</wp:Text2>";
$theData .= "<wp:Param>/Page2.xaml?NavigatedFrom=Toast Notification</wp:Param>";
$theData .= "</wp:Toast>";
$theData .= "</wp:Notification>";   

$header_array = array('X-WindowsPhone-Target' => 'toast','X-NotificationClass' => '2','Content-type:' => 'text/xml','Content-length:' => strlen($theData));
$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER,$header_array);
curl_setopt($ch, CURLOPT_URL,$uri);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$theData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//print_r($ch);
$server_output = curl_exec ($ch);
//echo $server_outout;
//curl_close ($ch);

if (curl_errno($ch)) 
{ 
        print "Error: " . curl_error($ch); 
}
else 
{ 
 // Show me the result 
    print $server_output; 
    curl_close($ch); 
} 
//file_put_contents($file, $theData);

&GT;

任何人都可以告诉我我在这里做错了什么?,我也尝试使用HTTPRequest Class来创建这个例子,但我很难配置php_http.dll扩展,看起来该文件有依赖或其损坏。尽管如此,对这一点的帮助会很棒。

2 个答案:

答案 0 :(得分:2)

您正在以错误的方式设置http标头($header_array)。使用这个。

$header_array = array(
  'X-WindowsPhone-Target: toast',
  'X-NotificationClass: 2',
  'Content-type: text/xml'
);

如果这不起作用,请将text/xml从上方更改为application/xml

答案 1 :(得分:0)

尝试使用urlencode并为POST首先准备变量

$postedfield="MYPOST=".urlencode($theData);

然后使用此变量

curl_setopt($ch, CURLOPT_POSTFIELDS,$postedfield);

并解码发布的值