首页 > 解决方案 > 如何在 HTTP/1.1 中使用 PHP cURL

问题描述

我的服务器 cURL 版本在进行远程调用时比客户端的版本更新,客户端的服务器自动切换到 http/2,有什么办法可以强制使用 curl 和 http/1.1

如何将 cURL HTTP 版本设置为 1.1,我通过在代码中添加以下设置进行了测试,但添加后 curl 停止工作。各种帮助都是可观的。提前致谢。

 curl_setopt($ch, CURLOPT_HTTP_VERSION, '1.1');
 curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

有什么办法可以将 curl 与 HTTP 1.1 一起使用?

我的服务器版本是

PHP 版本 7.2.16

cURL 信息 7.62.0

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

//curl_setopt($ch, CURLOPT_HTTP_VERSION, '1.1');
//curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
curl_setopt($ch, CURLOPT_TIMEOUT, 2400);  */
curl_setopt($ch,CURLOPT_HTTPHEADER, array(
   //  "http:1.1",
  'http' => array(
     'timeout' => 5,
     'protocol_version' => 1.1,
     'header' => 'Connection: close'
   ),
   "Content-Type: text/event-stream",
   "cache-control:no-cache",
   "Access-Control-Allow-Origin:*",
   'Authorization: Basic '. base64_encode($user.':'.$pass)
 ));


 $error  = 0;
 $result = curl_exec($ch);
 $info  = curl_getinfo($ch);
 $err   = curl_errno($ch);

客户技术团队回复:问题是 -> 您从 1.1 版开始,然后更改为 2 版

使用HTTP2,服务器支持多用

连接状态改变(HTTP/2 确认)

标签: phpcurlserver-sent-eventsphp-curl

解决方案


根据curl_setopt()的文档,代码

curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

应该是正确的。“卷曲停止工作”是什么意思?你得到的实际错误是什么?您还可以尝试提取有关错误的更多详细信息:

# before curl_exec():
error_reporting(~0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $filehandle);
# maybe also: curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
# maybe also: curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

# after curl_exec():
$curl_error = curl_error($ch);
$curl_error_number = curl_errno($ch);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

推荐阅读