Google自定义搜索API PHP curl Post XML HTTP 411错误


Google Custom Search API PHP curl Post XML HTTP 411 error

我尝试了几种不同的方法,用我的xml发送POST请求,为我的谷歌自定义搜索添加注释。我尝试过的每一种不同的方法都会导致HTTP411错误(POST请求需要一个Content-length头)。这是我当前的代码:

    <?php
    $ch = curl_init();
    $url = 'https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email=****&Passwd=*****&service=cprose&source=ednovo-classadmin-1';
    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];
    echo "got token: $authToken<br>";
    $annotation = $_POST['annotation'];
    $label = $_POST['label'];
    $href = $_POST['href'];
    curl_close($ch);
    $data ='<Batch>' .
                '<Add>' .
                    '<Annotations>' .
                        '<Annotation about = "' . $annotation . '">' .
                            '<Label name = "' . $label . '" />' .
                        '</Annotation>' .
                    '</Annotations>' .
                '</Add>' .
            '</Batch>';
   $url = "http://www.google.com/cse/api/default/annotations/";
    curl_setopt($ch, CURLOPT_URL, $url);
    $length = strlen($data);
    $header = array("Authorization: GoogleLogin auth=" . $authToken, "Content-Type: text/xml","Content-Length: " . $length);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    if ( curl_errno($ch) ) {
    $result = 'cURL ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
} else {
    $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    switch($returnCode){
        case 200:
            break;
        default:
            $result = 'HTTP ERROR -> ' . $returnCode;
            break;
    }
}
    echo $result;
?>

我很感激你的帮助。

谢谢。


我很感激你的帮助,因为这是我的问题之一。然而,即使在使用init并更改了头之后,它仍然会给我同样的HTTP411错误。你还有其他想法吗?非常感谢。

您在第一次请求ClientLogin后调用了curl_close($ch);,但忘记为第二次请求再次调用$ch = curl_init();。添加您不需要放置Content-Length标题字段;curl在设置post字段/数据时自动填充。您也可以尝试在Authorization字段中的auth值上添加引号。

$header = array('Authorization: GoogleLogin auth="'. $authToken.'"', "Content-Type: text/xml");

发布代码时,请始终删除您的谷歌应用程序登录凭据。

这不应该是[0]吗?也许不是,只是一个建议。

 $authToken = $authTokenArray[1];

仍在为你想办法。。。。