我已经在命令行上执行了此CURL,它成功在CMS中创建了内容(Drupal 9)。
curl \
--user username:9aqW72MUbFQR4EYh \
--header 'Accept: application/vnd.api+json' \
--header 'Content-type: application/vnd.api+json' \
--request POST http://www.domain.drupal/jsonapi/node/article \
--data-binary @payload.json
和JSON文件为:
{
"data": {
"type": "node--article",
"attributes": {
"title": "My custom title",
"body": {
"value": "Custom value",
"format": "plain_text"
}
}
}
}
正在创建魅力和数据。 我一直在尝试在GuzzleHttp中执行此操作,但无法使其正常工作。
Get正在工作: 需要'vendor / autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$url = 'http://www.domain.drupal';
$content_client = new GuzzleHttp\Client([
'base_uri' => $url,
'timeout' => 20.0,
]);
$res = $content_client->request('GET', '/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746');
对于POST,我可能有大约10个版本的反复试验,但没有任何效果。 如何将JSON /内容发布到Drupal,或者如何在Guzzle中正确实现CURL?
答案 0 :(得分:0)
如果您希望简单的发布请求发送带有标头的json正文,则无需使用Psr7请求即可轻松完成。 Guzzle使用PSR-7作为HTTP消息接口。
use GuzzleHttp\Client;
$url = 'http://www.domain.drupal';
$content_client = new Client([
'base_uri' => $url,
'timeout' => 20.0,
]);
$headers = [
'Content-type' => 'application/vnd.api+json',
'Accept' => 'application/vnd.api+json'
];
$payload['data'] = [
'type' => 'node--article',
'attributes' => [
"title" => "My custom title",
"body" => [
"value" => "Custom value",
"format" => "plain_text"
]
]
];
$guzzleResponse = $content_client->post('/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746', [
'json' => json_encode($payload),
'headers' => $headers
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody());
}
您可以使用RequestException将其写在try catch块中(有关更多信息,请参见此Catching exceptions from Guzzle。)