如何在PHP中为这个curl操作创建RESTAPI
我想通过php执行这个简单的curl操作我怎么能在简单的php中执行这个呢?不是任何框架,我能在简单的php中执行吗?或者我需要这个框架吗如何在PHP中为这个curl操作创建RESTAPI,php,json,curl,Php,Json,Curl,我想通过php执行这个简单的curl操作我怎么能在简单的php中执行这个呢?不是任何框架,我能在简单的php中执行吗?或者我需要这个框架吗 curl -XPOST localhost:12060/repository/schema/fieldType -H 'Content-Type: application/json' -d ' { action: "create", fieldType: { name: "n$name", valueType: { primitive
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);
?>
你的问题在于:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{json: $fieldString}"));
$fieldString
实际上并不是其名称所暗示的字符串。此时它仍然是一个数组。您正试图用Array
作为数据重新编码一个损坏的伪json字符串。不行
相反,使用此选项可以获得所需的(?)效果:
你的问题在于:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{json: $fieldString}"));
$fieldString
实际上并不是其名称所暗示的字符串。此时它仍然是一个数组。您正试图用Array
作为数据重新编码一个损坏的伪json字符串。不行
相反,使用此选项可以获得所需的(?)效果:
将头更改为头,但现在我在JSON错误错误错误请求400中收到错误。错误,这是JSON{“消息”:“无效的限定名,不包含$:n”,}的一部分,但当我运行CURL时,它会给我409个关于该项已存在的错误。请阅读并理解错误消息。--对
$fieldString
数据数组使用单引号。(或者全部,或者只是一个使用字符串插值的条目。)好的,问题是n$name在单引号更改的头中添加了这个,但是现在我在JSON错误错误请求400中得到了一个错误。错误,这是JSON{“message”的一部分:“无效的限定名,不包含$:n”,},但是当我运行CURL时,它给出了409个关于该条目已经存在的错误。请阅读并理解错误消息。-对$fieldString
数据数组使用单引号。(或者全部,或者只是一个使用字符串插值的条目。)好的,问题是n$name在单引号中添加了这个
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fieldString));