我正在尝试通过使用 php 和 cURL 发布 xml 以编程方式将注释(要搜索的站点)添加到我的谷歌自定义搜索引擎。根据他们的开发人员文档,我需要做的就是:
POST http://www.google.com/cse/api/default/annotations/
Content-Type: text/xml
Authorization: GoogleLogin auth="IM6F7Cx2fo0TAiwlhNVdSE8Ov8hw6aHV"
<Batch>
<Add>
<Annotations>
<Annotation about="http://www.solarenergy.org/*">
<Label name="_cse_solar_example"/>
</Annotation>
<Annotation about="http://www.solarfacts.net/*">
<Label name="_cse_solar_example"/>
</Annotation>
<Annotation about="http://en.wikipedia.org/wiki/*">
<Label name="_cse_exclude_solar_example"/>
</Annotation>
</Annotations>
</Add>
</Batch>
但是,当我使用以下代码时,我收到错误 411,“POST 请求需要 Content-length 标头”
function getAuthorizationToken(){
$ch = curl_init();
$url = 'https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email=***&Passwd=***&service=cprose&source=***';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$authTokenData = curl_exec($ch);
$authTokenArray = explode('Auth=', $authTokenData);
$authToken = $authTokenArray[1];
curl_close($ch);
return $authToken;
}
$authToken = getAuthorizationToken();
$url = 'http://www.google.com/cse/api/default/annotations/';
$xml_data = '<?XML version="1.0"?>
<Batch>
<Add>
<Annotations>
<Annotation about="http://www.solarenergy.org/*">
<Label name="_cse_solar_example"/>
</Annotation>
<Annotation about="http://www.solarfacts.net/*">
<Label name="_cse_solar_example"/>
</Annotation>
<Annotation about="http://en.wikipedia.org/wiki/*">
<Label name="_cse_exclude_solar_example"/>
</Annotation>
</Annotations>
</Add>
</Batch>';
$length = strlen($xml_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Authorization: GoogleLogin auth=". $authToken, "Content-Type: text/xml", "Content-Length: " . $length));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
$result = curl_exec($ch);
curl_close($ch);
echo $result;
我一直在努力解决这个问题很长一段时间,我将非常感谢任何帮助。
谢谢