2013-01-23 46 views
1

我試圖使用路徑desire2learn:創建用戶API路徑

POST /d2l/api/lp/(D2LVERSION: version)/users/ 

和我遇到了一個錯誤。我希望在文檔中沒有我缺少的東西,因爲從我可以告訴,這應該工作。

HTTP/1.1 400 Bad request 
Cache-Control: private 
Content-Length: 0 
Server: Microsoft-IIS/7.5 
X-XSS-Protection: 0 
X-Powered-By: ASP.NET 
Date: Wed, 23 Jan 2013 18:37:07 GMT 

的數據我送這個樣子的:

{ 
    "OrgDefinedId":"190006002", 
    "FirstName":"Jesty", 
    "MiddleName":"Q", 
    "LastName":"McTest", 
    "ExternalEmail":"[email protected]", 
    "UserName":"190006002", 
    "RoleId":115, 
    "IsActive":true, 
    "SendCreationEmail":true 
} 

我的PHP代碼看起來像這樣的時刻:

$random_hash = "xxBOUNDARYxx"; 
    $request ="--".$random_hash. 
       "\r\nContent-Type: application/json\r\n\r\n$data\r\n\r\n--". 
       $random_hash; 

    $length=strlen($request); 
    $url = $opContext->createAuthenticatedUri($url,"POST"); 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLINFO_HEADER_OUT, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("HTTP/1.1", "Content-Type: multipart/form-data; boundary=xxBOUNDARYxx","Content-Length:".$length)); 
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST,true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 
    return curl_exec($ch);  

回答

1

好,幾個小時的修修補補之後我想通出來。我發佈的原始代碼是基於通過API發佈配置文件圖像的代碼。剛發佈JSON的代碼要簡單得多。以下是通過POST方法將JSON發送至Valence的通用PHP函數

/* 
* $opContext is your user context object 
* $url is the route 
* $data is the well formed JSON in a string (use json_encode()) 
* $ct is the count of json fields 
*/ 

static function basic_post($opContext,$url,$data,$ct){ 
    $url = $opContext->createAuthenticatedUri($url,"POST"); 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLINFO_HEADER_OUT, true); 
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST,$ct); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 
    return curl_exec($ch); 
} 
+0

這是正確的。當你需要發送的只是一個標準的JSON結構時,你只需將Content-Type設置爲'application/json'併發送JSON即可。如果您需要發佈文件數據,那麼通常需要一個'multipart-mixed'內容類型,第一部分是文件的JSON描述符,第二部分是文件數據。 –

+0

有什麼不錯的是,我現在有用於獲取,放置,發佈和刪除價的通用函數。所以我有一個很好的抽象層,讓我專注於手頭的任務,而不是正確設置捲曲。 – Johnnygizmo

+0

我完全同意;這是我將'data'和'service'輔助模塊添加到Python客戶端SDK的原因之一。我不能聲稱他們寫得很好,因爲我是一個Python新手,但是這幫助我解決了同樣的問題。 –