2011-06-10 36 views
1

我已經嘗試了幾種不同的方法發送一個POST請求與我的xml添加註釋到我的谷歌自定義搜索。我嘗試過的每種不同方法都會導致HTTP 411錯誤(POST請求需要Content-length標頭)。這是我目前的代碼:谷歌自定義搜索API PHP curl發佈XML HTTP 411錯誤

<?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並更改標題之後,它仍然會給我提供相同的HTTP 411錯誤。你還有其他建議嗎?謝謝一堆。

+0

你不需要設置Content-Length頭部cURL是否自動運行 – Arvin 2011-06-10 04:47:25

回答

0

不應該是[0]嗎?也許不是,只是一個建議。

$authToken = $authTokenArray[1]; 

還在研究認定它爲你....

+0

這是正確的,這裏是ClientLogin http://code.google.com/apis/accounts/docs/AuthForInstalledApps的響應文檔。 HTML#響應 – Arvin 2011-06-10 04:44:03

1

您的ClientLogin的第一次請求之後調用curl_close($ch);,但你忘了第二個要求再做一個$ch = curl_init();。添加你不需要放置Content-Length標題字段; curl在設置後期字段/數據時自動填充此內容。您也可以嘗試在授權字段中的授權值上添加引號。

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

並且在發佈代碼時始終刪除您的Google Apps登錄憑據。