2012-07-29 126 views
3

我想使用REST API和PHP/cURL更新一些自定義字段。JIRA使用REST,PHP和cURL更新自定義字段

我想知道如果我可能在沒有意識到的情況下編輯了某些東西,而我昨天(我認爲)在「有效」的下面有一些東西,現在不起作用。

我得到使用不同的「方法」不同的響應,從:

  1. 我得到這個一個使用POST方法,因爲它是註釋掉以下。

    HTTP 405 - 所請求的 資源()不允許指定的HTTP方法。

  2. 如果我使用註釋掉的PUT方法,並將POST註釋掉,我會得到這一個。

    {"status-code":500,"message":"Read timed out"} 
    
  3. 而這一個混合和匹配PUT和POST。

    {"errorMessages":["No content to map to Object due to end of input"]} 
    

我缺少/做錯了嗎?我正在使用下面的代碼:

<?php 

$username = 'username'; 
$password = 'password'; 

$url = "https://example.com/rest/api/2/issue/PROJ-827"; 
$ch = curl_init(); 

$headers = array(
    'Accept: application/json', 
    'Content-Type: application/json' 
); 

$test = "This is the content of the custom field."; 

$data = <<<JSON 
{ 
    "fields": { 
     "customfield_11334" : ["$test"] 
    } 
} 
JSON; 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
// Also tried, with the above two lines commented out... 
// curl_setopt($ch, CURLOPT_PUT, 1); 
// curl_setopt($ch, CURLOPT_INFILE, $data); 
// curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data)); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); 

$result = curl_exec($ch); 
$ch_error = curl_error($ch); 

if ($ch_error) { 
    echo "cURL Error: $ch_error"; 
} else { 
    echo $result; 
} 

curl_close($ch); 

?> 

回答

8

這裏的問題是PHP的cURL API不是特別直觀。

你可能會認爲,因爲POST請求主體使用以下選項 一個PUT請求將被做了同樣的方式發送:

// works for sending a POST request 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

// DOES NOT work to send a PUT request 
curl_setopt($ch, CURLOPT_PUT, 1); 
curl_setopt($ch, CURLOPT_PUTFIELDS, $data); 

相反,發送PUT請求(具有相關聯的身體數據),您需要具備以下條件:即使你發送一個PUT請求

// The correct way to send a PUT request 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

注意,你仍然必須使用CURLOPT_POSTFIELDS 選項發送你的PUT請求體。這是一個令人困惑和不一致的過程,但是如果您想使用PHP cURL綁定,那麼這就是您已經獲得的 。

按照relevant manual entrydocs,在CURLOPT_PUT選項似乎只對直接把文件工作:

TRUE以HTTP PUT文件。 PUT文件必須使用CURLOPT_INFILE和CURLOPT_INFILESIZE進行設置。

更好的選擇恕我直言,是使用自定義流包裝器的HTTP客戶端操作。這會帶來 的額外好處,即不會使您的應用程序依賴於底層的libcurl庫。不過,這樣的實現超出了這個問題的範圍。如果你有興趣 開發流包裝解決方案,Google是你的朋友。

+0

這就像你讀了我的腦海,知道問題來了......「:P'再次感謝。 – 2012-07-29 19:47:11

+0

Streams:[HTTP上下文選項](http://de.php.net/manual/en/context.http.php)和['stream_context_create()'](http://de.php.net/stream_context_create) – 2012-07-29 20:29:47

相關問題