php - Guzzle 不发送发布请求
问题描述
我正在使用带有 Guzzle 的 PHP。我有这个代码:
$client = new Client();
$request = new \GuzzleHttp\Psr7\Request('POST', 'http://localhost/async-post/tester.php',[
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => [
'action' => 'TestFunction'
],
]);
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
由于某种原因,Guzzle 不发送 POST 参数。有什么建议吗?
谢谢 :)
解决方案
我看到两件事。参数必须以字符串 ( json_encode
) 的形式出现,而且您还将它们作为 HEADER 的一部分,而不是 BODY。
然后我添加一个函数来处理响应ResponseInterface
$client = new Client();
$request = new Request('POST', 'https://google.com', ['Content-Type' => 'application/x-www-form-urlencoded'], json_encode(['form_params' => ['s' => 'abc',] ]));
/** @var Promise\PromiseInterface $response */
$response = $client->sendAsync($request);
$response->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
$response->wait();
在此测试中,Google 以客户端错误响应:POST https://google.com
导致405 Method Not Allowed
但是没关系。谷歌不接受这样的请求。
推荐阅读
- ios - 如何从 iOS Swift 中的可编码模型创建嵌套 json?
- regex - 操作字符串以创建新列 pandas 的更好方法
- azure-devops - Azure Rest API 问题
- javascript - 使用 videoJS 检测 VOD 中的当前片段 ID
- javascript - 删除对象数组中的对象键和值
- node.js - 仅当我使用“/”(不在其他路径中)时,Apache ProxyPass 才加载资源
- java - 使用 Selenium Java 单击聊天按钮
- javascript - 在着色器中更改矩形的大小和比例
- ios - 如何滚动cupertino选择器自动颤动?
- javascript - 将 forwardRef 与 proptypes 和 eslint 一起使用