有人能写一个PHP脚本来重现这个linux shell命令的功能吗?
curl -X POST -u "USERNAME:PASS" '
-H "Content-Type: application/json" '
--data '{"aps": {"alert": "this is a message"}}' '
https://mywebsite.com/push/service/
我想我几乎在代码中得到了它,但我不确定如何处理--data
属性。
到目前为止,我的代码是这样的:
$headers = array();
$headers[] = "Content-Type: application/json";
$body = '{"aps":{"alert":"this is a message"}}';
$ch = curl_init();
// Set the cURL options
curl_setopt($ch, CURLOPT_URL, "https://mywebsite.com/push/service/");
curl_setopt($ch, CURLOPT_USERPWD, "USERNAME:PASSWORD");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
print_r($result);
一个通用规则:使用"--libcurl example.c"选项获取curl,为使用libcurl的c程序生成源代码。正如您将看到的,API与PHP/CURL非常相似,然后您应该很快意识到——数据转换为CURLOPT_POSTFIELDS。
哦,你会注意到-X的用法是完全多余的!;-)
中的示例
http://code.google.com/apis/gdata/articles/using_cURL.html
curl https://www.google.com/accounts/ClientLogin '
--data-urlencode Email=brad.gushue@example.com --data-urlencode Passwd=new+foundland '
-d accountType=GOOGLE '
-d source=Google-cURL-Example '
-d service=lh2