【问题标题】:Guzzle POST request results in 500 error even though Curl for that worksGuzzle POST 请求导致 500 错误,即使 Curl 有效
【发布时间】:2018-05-27 04:02:14
【问题描述】:

我有下面的 PHP 代码块用于访问 POST API

$client = new \GuzzleHttp\Client(['debug'=>true]);
$response = $client->request(
    $request_method,
    $request_url,
    [
        'json' => $request_data,
        'http_errors' => false
    ]
);

$http_code = $response->getStatusCode();

这会导致来自服务器的 500 响应,尽管调试日志中正确列出了所有标头,如下所示:

* Hostname was NOT found in DNS cache
*   Trying 52.xxx.xx.xx...
* Connected to <<hostname>> (52.xxx.xx.xx) port 80 (#0)
> POST /api/rest/auth_key HTTP/1.1
User-Agent: GuzzleHttp/6.2.1 curl/7.38.0 PHP/7.0.9-1~dotdeb+8.1
Content-Type: application/json
Host: <<hostname>>
Content-Length: 42

* upload completely sent off: 42 out of 42 bytes

$request_url 是 POST 请求的完整 URL。
$request_data 是要发送的 JSON 内容(PHP 关联数组)。
$request_method 是 'POST'

即使我从请求中删除 json 数据,期望从 API 获得 400 响应,我仍然会收到相同的 500 错误。 通过 Curl 触发的相同请求适用于以下代码:

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $request_url,
  CURLOPT_CUSTOMREQUEST => $request_method,
  CURLOPT_POSTFIELDS => json_encode($request_data),
  CURLOPT_HTTPHEADER => [
    "content-type: application/json"
  ],
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

一直在尝试调试它很长一段时间,甚至在 SO 中寻找类似的参考,但无济于事。在这方面的任何帮助都会很棒。

【问题讨论】:

    标签: php json curl post guzzle


    【解决方案1】:

    我无法发表评论,因为我没有足够的声誉,所以如果这不能回答您的问题或解决问题,请提前抱歉。

    我遇到了类似的问题,cURL 工作没有问题,但我收到 500 响应或 400 错误请求(请求太长)。事实证明,当您在 POST 请求的第三个参数中包含 json 数据时,它被包含在请求的标头中。

    文档中有一些示例,其中GuzzleHttp\Psr7\Request 类的第四个参数用作请求的主体(请参阅http://docs.guzzlephp.org/en/stable/psr7.html)。一旦我使用它并在标题中明确设置内容类型,我的问题就解决了。

    这意味着您的请求将如下所示:

    $response = $client->request(
        $request_method,
        $request_url,
        ['Content-Type'=>'application/json'],
        json_encode($request_data)
    );
    

    希望这对你也有帮助!

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2015-07-11
      相关资源
      最近更新 更多