【问题标题】:PHP cURL request fails, but works with Postman/curl from BashPHP cURL 请求失败,但适用于 Bash 中的 Postman/curl
【发布时间】:2015-01-06 04:44:01
【问题描述】:

我遇到了一个很奇怪的情况。在 Postman 中向 Web 服务发出请求可以正常工作(x-www-form-urlencoded),只需几个参数。

但是,当我使用 PHP cURL 发出此请求时,请求失败并出现类似以下的响应:

Failed to Connect, fopen(http://10.0.0.8:8080/posts?foo=bar&bar=baz): failed to open stream: HTTP request failed! 

web服务貌似是用PHP写的,端点如http://foo.com/service.php

Postman 将在 100% 的时间内工作,从 Bash 发出的 cURL 请求在 100% 的时间内工作。

对我来说,它尝试解析内部 IP 地址并且仅在使用 php cURL 库时才会失败,这非常奇怪。

希望有人可以对此有所了解或以前经历过。我已经尝试了几乎所有可以想象的 curl 选项来让它工作,但没有运气。任何帮助将不胜感激。

代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::SERVICE_ENDPOINT);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);

var_dump(curl_exec($ch));
die;

详细输出:

HTTP/1.1 200 OK
Date: Tue, 06 Jan 2015 09:27:20 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Last-Modified: Tue, 06 Jan 2015 09:27:20 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 324
Content-Type: text/html

Failed to Connect, fopen(http://10.0.0.8:8080/posts?foo=bar&bar=baz): failed to open stream: HTTP request failed!

【问题讨论】:

  • 您可以通过 curl 请求发送某些内容以调试实际发生的情况,尝试将其替换为您的 curl_exec():curl_setopt(CURLOPT_HEADER, true);curl_setopt(CURLOPT_FAILONERROR, FALSE); var_dump(curl_exec());die;
  • 你有没有使用任何代理?
  • 我没有使用代理。在原始消息中添加了调试信息。
  • 请显示您用于组装和发送请求的 PHP 代码
  • 我已经更新了代码。

标签: php curl


【解决方案1】:

curl 命令没问题,但是远程服务器上的代码尝试使用fopen 下载一些文件。这会失败,并且错误消息会作为对调用代码的响应的一部分返回。看起来远程代码试图根据从客户端接收到的一些输入打开一个 URL; curl 命令的输入与 Postman 的输入不同。要准确找出 HTTP 标头或 POST 内容中的哪些元素是罪魁祸首,您需要查看远程服务器代码 (service.php) 或通过将 Postman 请求的确切内容与的 CURL 请求。

【讨论】:

  • 谢谢。我不敢相信我忽略了这一点。事实证明,设置为布尔值 true 的参数导致了该问题。将其更改为字符串解决了该问题。再次感谢!
  • 你能指出它是哪个参数吗?我面临同样的错误,但仍然无法弄清楚。这是我正在使用的代码: $data2 = 'redirect_uri=xxxmyredirecturixxx&client_id=xxxxmyclientidxxx&client_secret=xxxxmyclientsecretxxxxx&refresh_token=xxxrefreshtokenofmyaccountxxx&type=refresh'; curl_setopt($ch, CURLOPT_URL, 'launchpad.37signals.com/authorization/token'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
猜你喜欢
  • 1970-01-01
  • 2017-07-16
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 2017-05-29
  • 2017-06-16
相关资源
最近更新 更多