2011-09-02 84 views
1

我想通過php執行這個簡單的捲曲操作我該如何在簡單的PHP中執行此操作,而不是任何框架,我可以在簡單的PHP中執行操作還是需要該框架?如何在PHP中爲此捲曲操作創建REST API

curl -XPOST localhost:12060/repository/schema/fieldType -H 'Content-Type: application/json' -d ' 
{ 
    action: "create", 
    fieldType: { 
    name: "n$name", 
    valueType: { primitive: "STRING" }, 
    scope: "versioned", 
    namespaces: { "my.demo": "n" } 
    } 
}' -D - 

我的嘗試是:

<?php 
$url="localhost:12060/repository/schema/fieldType";  
//open connection 
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page 
CURLOPT_HEADER => false, // don't return headers 
CURLOPT_FOLLOWLOCATION => true, // follow redirects 
CURLOPT_ENCODING => "", // handle all encodings 
CURLOPT_USERAGENT => "spider", // who am i 
CURLOPT_AUTOREFERER => true, // set referer on redirect 
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect 
CURLOPT_TIMEOUT => 120, // timeout on response 
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects 
); 
$ch = curl_init(); 

//set the url, number of POST vars, POST data 
curl_setopt($ch,CURLOPT_URL,$url); 
$fieldString=array(
    "action"=> "create", 
    "fieldType"=>array(
     "name"=> "n$name", 
     "valueType"=> array("primitive"=> "STRING"), 
     "scope"=> "versioned", 
     "namespaces"=> array("my.demo"=> "n") 
    ) 
); 
//for some diff 
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_VERBOSE, TRUE); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{json: $fieldString}")); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt_array($ch, $options); 
//execute post 
$result = curl_exec($ch); 
$header = curl_getinfo($ch); 
echo $result; 
//close connection 
curl_close($ch); 




?> 

但它給我這個

The given resource variant is not supported.Please use one of the following: * Variant[mediaType=application/json, language=null, encoding=null] 

回答

1

你的問題就在這裏:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{json: $fieldString}")); 

$fieldString並不是真正的字符串作爲它的名字im層數。這仍然是一個數組。並且您正試圖重新編碼一個損壞的人造json字符串,只有Array作爲數據。將無法工作。

而是用它來得到想要的效果(?):

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fieldString)); 
+0

改變,但仍是同樣的錯誤? – XMen

+0

http://stackoverflow.com/questions/5357900/content-type-not-changing-with-curlopt-httpheaders – mario

+0

改變頭到頭,但現在我得到一個JSON錯誤錯誤請求400沒有。錯誤,這是JSON的一部分{「message」:「無效的限定名稱,不包含$:n」,},但是當我通過CURL運行時,它給我提供了有關該條目已存在的409錯誤。 – XMen