【问题标题】:How to make this work with Guzzle如何使用 Guzzle 进行这项工作
【发布时间】:2018-08-18 05:32:25
【问题描述】:

我正在尝试使用 Guzzle 而不是 curl 来发出 API 请求。由于某种原因,此 API 要求在 post 字段值前面加上 request=。如何使用 Guzzle 做到这一点?

以下是使用 curl 的方法:

$postfields = json_encode(array('field1' => 'some value'));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://someapi.com/PostRequest');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$postfields");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
$curlerror = curl_errno($ch);
if (!empty($curlerror))
{
    echo 'curl error: ' . $curlerror;
}
curl_close($ch);

echo $response;

我已经尝试过了,但 API 以无效格式错误响应。

$postfields = json_encode($request);

$client = new Client();
$response = $client->request('POST', 'https://someapi.com/PostRequest', array('request' => $postfields));

同样的错误。

    $postfields = json_encode($request);

    $client = new Client();
    $response = $client->request('POST', 'https://someapi.com/PostRequest', array("request=$postfields"));
    print_r($response);

如果我尝试这个 Guzzle 会给出参数 3 不是数组的错误。

$postfields = json_encode($request);

$client = new Client();
$response = $client->request('POST', 'https://someapi.com/PostRequest', "request=$postfields");
print_r($response);

这可能是 API 设计不佳的情况,我无法使用 Guzzle。

【问题讨论】:

  • 试试不json编码$postfields?
  • api 期望它是 json 编码的

标签: php guzzle


【解决方案1】:

老实说,我很惊讶您的 Curl 示例有效,因为您应该 urlencode 数据。

但是,问题是第三个参数不是要发布的数据。是一个options数组,其中POST数据是一个option,需要用keyform_params发送:

$client->request('POST', 'https://someapi.com/PostRequest', array('query'=>array('request' => $postfields)));
// or
$client->request('POST', 'https://someapi.com/PostRequest', ['form_parms'=>['request'=>$postfields]]);

这是specified in the documentation

【讨论】:

  • 感谢您的链接。我现在确实了解不同的选择。查询在这里不起作用,因为它只是将 json 字符串作为查询参数添加到 URL。我也尝试了各种其他选项,但没有一个可行。我很确定这是一个糟糕的 API 设计案例,我将无法使用 guzzle。
  • @TomVaughan 你说得对:应该是form_params 而不是query。答案已更新。这不是 API 或客户端的问题。
猜你喜欢
  • 1970-01-01
  • 2018-07-24
  • 2019-02-03
  • 2011-01-14
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多