【问题标题】:Transform a CURL POST request to GuzzleHttp Post将 CURL POST 请求转换为 GuzzleHttp Post
【发布时间】:2021-02-14 05:51:21
【问题描述】:

我在命令行上执行了这个 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 中执行此操作,但无法正常工作。

获取正在运行: 需要'供应商/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?

【问题讨论】:

  • 下面的答案对你有用吗?

标签: php curl drupal guzzle


【解决方案1】:

如果您想要一个简单的 post 请求来发送带有您的标头的 json 正文,您可以不使用 Psr7 Request 简单地做到这一点。 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 以了解更多信息。)

【讨论】:

  • 如果你想使用 Guzzle Pool 可以直接使用 psr7 请求
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多