Guzzle POST请求导致500错误,即使Curl for that工作

时间:2017-12-13 09:54:30

标签: php json curl post guzzle

我有以下用于命名POST API的PHP代码

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

$http_code = $response->getStatusCode();

这导致服务器发出500响应,尽管所有Headers都在调试日志中正确列出,如下所示:

* 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请求的完整网址 $ request_data 是要发送的JSON内容(PHP关联数组) $ request_method &#39; POST&#39;

即使我从请求中删除了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中寻找类似的参考,但无济于事。在这方面的任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

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

我遇到了类似的问题,其中cURL没有问题,但我得到的是500响应或400 Bad Request(请求太长)。事实证明,当您在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)
);

希望这也会帮助你!

相关问题