2015-07-20 157 views
2

我想使用php curl將json數據發佈到GCM(Google Cloud Messaging)服務器。下面是我的代碼snipppet411 - 使用PHP curl發佈json數據時需要的長度錯誤

$url="https://android.googleapis.com/gcm/send"; 
$fields=array('registration_ids'=>$registration_ids,'data'=>$message); 
$headers=array('Authorization:key='. GOOGLE_API_KEY, 
       'Content-Type:application/json', 
       'Content-Length: '.strlen(json_encode($fields))); 
$ch=curl_init(); 
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST"); 
curl_setopt($ch,CURLOPT_POST,true); 
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); 
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(fields)); 
$result=curl_exec($ch); 
curl_close($ch); 
echo $result; 

在運行該腳本,我得到一個錯誤說

Error 411(Length Required) !! 1 

我搜索一些論壇,但沒有得到這個解決方案。誰能幫忙?

回答

0

奇怪的是,我找到了相同的PHP代碼,但它並沒有爲我抱怨。試試這裏的代碼並將其粘貼到http://phpfiddle.org/

<?php 


// API access key from Google API's Console 
define('API_ACCESS_KEY', 'Axxxxxxxxxxxxxxxxxx'); 


$registrationIds = array("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); 

// prep the bundle 
$msg = array 
(
    'message'  => 'here is a message. message', 
    'title'   => 'This is a title. title', 
    'subtitle'  => 'This is a subtitle. subtitle', 
    'tickerText' => 'Ticker text here...Ticker text here...Ticker text here', 
    'vibrate' => 1, 
    'sound'  => 1 
); 

$fields = array 
(
    'registration_ids' => $registrationIds, 
    'data'    => $msg 
); 

$headers = array 
(
    'Authorization: key=' . API_ACCESS_KEY, 
    'Content-Type: application/json' 
); 

$ch = curl_init(); 
curl_setopt($ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send'); 
curl_setopt($ch,CURLOPT_POST, true); 
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields)); 
$result = curl_exec($ch); 
curl_close($ch); 

echo $result; 
?> 
相關問題