有人可以编写一个PHP脚本来重现这个linux shell命令的function吗?
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);
例如:
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
一般的规则是:使用“ –libcurl example.c”选项来获得curl来为将使用libcurl的C程序生成源代码。 这个API非常类似于PHP / CURL,您应该很快意识到–data会转换为CURLOPT_POSTFIELDS 。
哦,你会注意到-X的用法是完全多余的! 😉