2

我正在尝试使用 php curl 将 json 数据发布到 GCM(Google Cloud Messaging)服务器。下面是我的代码片段

$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

我搜索了几个论坛,但没有得到解决方案。任何人都可以帮忙吗?

4

1 回答 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;
?>
于 2015-10-29T19:18:37.800 回答