使用PHP curl如何获得400响应的响应主体 [英] Using PHP curl how does one get the response body for a 400 response
问题描述
我调用的api使用PHP代码400返回一个验证错误的json对象。我使用PHP的curl库实现了客户端,但是在错误 curl_exec
返回false 。
The api I'm calling returns a json object of validation errors with the HTTP code 400. I implemented the client using PHP's curl library, but on error curl_exec
returns false. How can I get the response body on error?
请注意,我设置的是 curl_setopt($ curl,CURLOPT_RETURNTRANSFER,true);
推荐答案
您可以取消设置 CURLOPT_FAILONERROR
一次。并将预期的错误状态代码添加到 CURLOPT_HTTP200ALIASES
也可能有帮助。
You can unset CURLOPT_FAILONERROR
for once. And adding your error status code to CURLOPT_HTTP200ALIASES
as expected might also help.
curl_setopt($conn, CURLOPT_FAILONERROR, false);
curl_setopt($conn, CURLOPT_HTTP200ALIASES, (array)400);
(libcurl也有一个 CURLOPT_ERRORBUFFER
您不能从PHP使用该选项。)
(libcurl also has a CURLOPT_ERRORBUFFER
, but you cannot use that option from PHP.)
Btw,curl在4xx错误的情况下不返回响应主体正确运行。不知道是否可以覆盖。因此,您可能需要迁移到 PEAR HTTP_Request2
或类似的HTTP请求类,您可以在其中偏离标准。
Btw, curl behaves correctly by not returning the response body in case of 4xx errors. Not sure if that can be overriden. So you might have to migrate to PEAR HTTP_Request2
or a similar HTTP request class where you can deviate from the standard.
这篇关于使用PHP curl如何获得400响应的响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!