如何在PHP中为这个curl操作创建REST API


How to create the REST API for this curl operation in PHP

我想通过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: "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] 

你的问题在这里:

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

$fieldString实际上并不是它的名字所暗示的字符串。此时它仍然是一个数组。你正试图重新编码一个混乱的伪json字符串,只有Array作为数据。行不通的。

可以用这个来获得想要的(?)效果:

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