简体   繁体   English

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

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

I want executed this simple curl operation through php how can i execute this in simple php not any framework , can i do it in simple php or do i need the framework? 我想通过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 -

what i tried is : 我尝试的是:

<?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);




?>

But it is giving me this 但这给了我

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

Your problem lies here: 您的问题出在这里:

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

The $fieldString is not actually an string as its name implies. $fieldString$fieldString实际上不是字符串。 It was an array at this point still. 此时仍然是一个数组。 And you are trying to reencode an mangled faux json string, with just Array as data. 而且您正在尝试重新编码一个假的json字符串,仅使用Array作为数据。 Won't work. 不行

Instead use this to get the desired(?) effect: 而是使用它来获得所需的效果?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM