【发布时间】: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 编码的