PHP Curl - 在不允许时接收 HTTP/0.9



当我尝试向苹果推送服务发送 HTTP/2.0 请求时,我偶然发现了一个奇怪的行为:

$http2ch = curl_init();
curl_setopt($http2ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($http2ch, CURLOPT_URL, 'https://api.push.apple.com/3/device/megauniquedevicetokendummy');
curl_setopt($http2ch, CURLOPT_PORT, 443);
curl_setopt($http2ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($http2ch, CURLOPT_POST, true);
curl_setopt($http2ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($http2ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($http2ch, CURLOPT_TIMEOUT, 30);
curl_setopt($http2ch, CURLOPT_HEADER, 1);
$result = curl_exec($http2ch);
if ($result === false) {
throw new Exception("Curl failed: " . curl_error($http2ch) . " | " . curl_getinfo($http2ch, CURLINFO_HTTP_CODE));
}

异常随消息一起引发: curl 失败:在不允许时收到 HTTP/0.9|0

我明确告诉curl在上面截取的代码的第二行上使用HTTP/2.0。 有没有人知道该错误消息的含义以及为什么 curl 使用如此旧的 HTTP 版本?

我使用的是 PHP 7.2 和 curl 版本 7.66.0。

当服务器是 grpc 服务器时,也会发生这种情况。 当 curl 针对 grpc 服务器或其他非 HTTP 服务器运行时,该服务器未响应 curl 期望的有效 HTTP 状态行,curl 将打印"不允许时已接收 HTTP/0.9"。

如果 curl 打印类似"未知协议"的东西而不是假设它是 0.9 可能会更好,因为如今遇到像 grpc 服务器这样的东西将比实际的 HTTP 0.9 服务器更常见。

我想通了。 确保使用 nghttp2 编译 curl。

如果您不确定,可以使用curl --version在终端上检查

如果你没有找到 nghttp2/{version},你需要用 nghttp2 再次编译 curl。

curl --version缺少 nghttp2 的示例:

curl 7.66.0 (amd64-portbld-freebsd12.0) libcurl/7.66.0 OpenSSL/1.1.1d zlib/1.2.11

curl --versionnghttp2 可用的示例中:

curl 7.64.1 (x86_64-apple-darwin19.0) libcurl/7.64.1 (SecureTransport) LibreSSL/2.8.3 zlib/1.2.11 nghttp2/1.39.2

我不认为它需要你以不同的方式编译一个版本的curl,而是设置允许http 0.9作为旧服务器的响应的选项。PHP 有一些关于"CURLOPT_HTTP09_ALLOWED"的注释,当您通过 https://www.php.net/manual/en/function.curl-setopt.php 发布问题时,这些注释可能会有所不同

为我克服错误的选项是:

curl_setopt($http2ch, CURLOPT_HTTP09_ALLOWED, true);

最新更新