HugeGraph應用(2):PHP 通過 Restful API訪問HugeGraph

在上一篇博客HugeGraph應用(1):安裝與配置中,已經完成了HugeGraph的安裝與配置,本篇博客介紹Web應用如何對HugeGraph進行訪問,HugeGraph目前只提供了java的客戶端,但是其他語言的應用可以使用 Restful API進行訪問,這裏以PHP爲例,使用curl進行http訪問:

詳細的API介紹請參見:https://hugegraph.github.io/hugegraph-doc/clients/hugegraph-api.html

一、GET請求:

$headers = array();
$headers[] = "Content-Type:application/json";

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, 'http://IP:8089/graphs/hugegraph/schema/propertykeys');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$res = curl_exec($curl);     

curl_close($curl);
print_r($res); 

二、POST請求:

$headers = array();
$headers[] = "Content-Type:application/json";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://IP:8089/graphs/hugegraph/schema/propertykeys');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
$post_data = json_encode(array(
	"name"=>"sex",
	"data_type"=>"INT",
	"cardinality"=>"SINGLE"
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$res = curl_exec($curl);
curl_close($curl);
print_r($res);

這裏需要注意的是:

1、一定要設置請求頭Content-Type:application/json;

2、post的參數要進行json編碼,或者直接使用json字符串;

三、直接執行gremlin語句:

通過API執行gremlin post和get兩種方法均可,這裏使用post方法:

$headers = array();
$headers[] = "Content-Type:application/json";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://IP:8089/gremlin');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_POST, 1);

$post_data = '{
    "gremlin": "hugegraph.traversal().V(\'1:marko\')",
    "bindings": {},
    "language": "gremlin-groovy",
    "aliases": {}
}';		

curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$res = curl_exec($curl);
$res = mb_convert_encoding($res,'UTF-8','UTF-8,GBK,GB2312,BIG5');
curl_close($curl);
print_r($res);

這裏注意一定要設置curl_setopt($curl, CURLOPT_ENCODING, 'gzip')。由於服務器返回的內容進行了壓縮,否則結果是亂碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章