如何在Symfony 6的POST请求中传递curl的-d参数数据
解决Symfony 6 HttpClient请求422错误的正确配置
你的问题出在Symfony HttpClient的参数配置上:data并不是官方支持的选项,导致表单数据没有被正确放入请求体,服务器因此返回422错误。
针对application/x-www-form-urlencoded类型的请求,有两种正确的配置方式:
方式一:使用form_params(推荐)
直接传参数数组,Symfony会自动处理URL编码并设置正确的Content-Type头:
$response = $this->client->request('POST', $url_target, [ 'headers' => [ 'Accept' => 'application/json', ], 'verify_peer' => false, 'verify_host' => false, 'form_params' => [ 'username' => 'some_user_name', 'password' => 'some_password' ] ]);
方式二:使用body传递预编码字符串
如果你已经有编码好的参数字符串,需要用body选项替代data,同时手动保留Content-Type头:
$response = $this->client->request('POST', $url_target, [ 'headers' => [ 'Accept' => 'application/json', 'Content-Type' => 'application/x-www-form-urlencoded', ], 'verify_peer' => false, 'verify_host' => false, 'body' => 'username=some_user_name&password=some_password' ]);
这两种方式都能将表单数据正确放入请求体,匹配你提供的curl请求逻辑,解决422错误。
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

