【问题标题】:Replicating cURL post in Guzzle在 Guzzle 中复制 cURL 帖子
【发布时间】:2016-12-20 09:12:05
【问题描述】:

我使用 cURL 将数据发布到 API,但我决定改用 Guzzle。使用 cURL 我会这样做

$data = 
"<Lead>
  <Name>$newProject->projectName</Name>
  <Description>$newProject->projectName</Description>
  <EstimatedValue>$newProject->projectValue</EstimatedValue>
</Lead>";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.someurl.com/lead.api/add?apiKey=12345&accountKey=12345");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: text/xml',
    'Content-Length: ' . strlen($data)
));

$output = curl_exec($ch);

这就是我目前正在尝试使用 Guzzle。

$data = "<Lead>
            <Name>$campaign->campaignName</Name>
            <Description>$campaign->campaignName</Description>
            <EstimatedValue>$campaign->campaignValue</EstimatedValue>
          </Lead>";

$client = new GuzzleHttp\Client();
$req = $client->request('POST', 'https://somurl', [
    'body' => $data,
    'headers' => [
        'Content-Type' => 'text/xml',
        'Content-Length' => strlen($data),
    ]
]);
$res = $client->send($req);
$output = $res->getBody()->getContents();

我面临的第一个问题是,它说明请求的争论 3 需要是一个数组,而我将它传递给一个字符串。那很好,但是我怎样才能发送我的 xml 块呢?另外,我想我可能没有正确设置标题?

我浏览了文档,看到参数 3 需要是一个数组,但我没有看到如何发布 XML 字符串。

任何建议表示赞赏。

谢谢

【问题讨论】:

  • $client-&gt;request('POST', 'http://whatever', ['body' =&gt; $data]);
  • 完美,谢谢。标记为答案,我会接受。你知道如何设置标题吗?#

标签: php laravel-5.2 guzzle


【解决方案1】:

您可以使用“body”参数创建一个数组:

$client->request('POST', 'http://whatever', ['body' => $data]);

阅读更多:http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=post#post-form-requests

要设置标题,您可以执行以下操作:

$response = $client->request('POST', 'http://whatever', [
    'body' => $data,
    'headers' => [
        'Content-Type' => 'text/xml',
        'Content-Length' => strlen($data),
    ]
]);
$output = $response->getBody()->getContents();

阅读更多:http://docs.guzzlephp.org/en/latest/request-options.html#headers

【讨论】:

  • 我正在尝试类似的东西,但我得到类型错误:传递给 GuzzleHttp\Client::send() 的参数 1 必须实现接口 Psr\Http\Message\RequestInterface
  • @kate_hudson 你不需要$client-&gt;send$client-&gt;request 自己会为您提出请求。见:cloud.githubusercontent.com/assets/1779189/17643835/…
猜你喜欢
  • 2019-01-25
  • 1970-01-01
  • 2019-01-21
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2023-02-12
  • 2016-04-20
  • 2016-05-15
相关资源
最近更新 更多