我尝试处理外部API和POST json数据。
public function execute()
{
// ...
try
{
$request = new Request();
$request->setUri($this->getUrl());
$request->setMethod('POST');
$request->setHeaders($request->getHeaders()->addHeaders($this->getHeaders()));
$client = new Client();
$client->setOptions(['sslverifypeer' => false]);
$client->setRawBody($this->getContent()); // content is JSON encoded
$response = $client->dispatch($request);
}
catch (\Exception $e)
{
throw new Exception(Exception::UNEXPECTED_ERROR, $e->getMessage());
}
var_dump($response); exit;
// ...
}
protected function getHeaders()
{
return [
'Content-Type' => 'application/json; charset=utf-8',
//'Content-Length' => strlen($this->getContent()),
'Accept' => 'application/json',
'Authorization' => Client::AUTH_BASIC . ' ' . base64_encode($this->username . ':' . $this->secret)
];
}
如果我没有发送Content-length
标头,则会抛出此错误The request must be chunked or have a content length
如果我发送,应用程序会抛出read timeout
错误
所有想法都将受到赞赏