411 - 使用PHP curl发布json数据时所需的长度错误

时间:2015-07-20 07:39:54

标签: php curl http-status-code-411

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

Set-ExecutionPolicy

在运行此脚本时,我收到错误消息

$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;

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

1 个答案:

答案 0 :(得分: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;
?>