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')。由于服务器返回的内容进行了压缩,否则结果是乱码。

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